<?php
class ControllerSaleOrder extends Controller {
	private $error = array();

	public function index() {
		$this->load->language('sale/order');

		$this->document->setTitle($this->language->get('heading_title'));

		$this->load->model('sale/order');
		$this->load->model('sale/stock_out');

		$this->getList();
	}

	public function add() {
		$this->load->language('sale/order');

		$this->document->setTitle($this->language->get('heading_title'));

		$this->load->model('sale/order');

		$this->getForm();
	}

	public function edit() {
		$this->load->language('sale/order');

		$this->document->setTitle($this->language->get('heading_title'));

		$this->load->model('sale/order');

		$this->getForm();
	}

	protected function getList() {
		if (isset($this->request->get['filter_order_id'])) {
			$filter_order_id = $this->request->get['filter_order_id'];
		} else {
			$filter_order_id = null;
		}

		if (isset($this->request->get['filter_customer'])) {
			$filter_customer = $this->request->get['filter_customer'];
		} else {
			$filter_customer = null;
		}

		if (isset($this->request->get['filter_order_status'])) {
			$filter_order_status = $this->request->get['filter_order_status'];
		} else {
			$filter_order_status = null;
		}

		if (isset($this->request->get['filter_verify_status'])) {
			$filter_verify_status = $this->request->get['filter_verify_status'];
		} else {
			$filter_verify_status = null;
		}

		if (isset($this->request->get['filter_total'])) {
			$filter_total = $this->request->get['filter_total'];
		} else {
			$filter_total = null;
		}

		if (isset($this->request->get['filter_is_pay'])) {
			$filter_is_pay = $this->request->get['filter_is_pay'];
		} else {
			$filter_is_pay = 3;
		}


		if (isset($this->request->get['filter_is_shelf_order'])) {
			$filter_is_shelf_order = $this->request->get['filter_is_shelf_order'];
		} else {
			$filter_is_shelf_order = 3;
		}

		if (isset($this->request->get['filter_date_added'])) {
			$filter_date_added = $this->request->get['filter_date_added'];
		} else {
			$filter_date_added = null;
		}

		if (isset($this->request->get['filter_date_modified'])) {
			$filter_date_modified = $this->request->get['filter_date_modified'];
		} else {
			$filter_date_modified = null;
		}

		if (isset($this->request->get['filter_date_start'])) {
			$filter_date_start = $this->request->get['filter_date_start'];
		} else {
			$filter_date_start = null;
		}

		if (isset($this->request->get['filter_date_end'])) {
			$filter_date_end = $this->request->get['filter_date_end'];
		} else {
			$filter_date_end = null;
		}

		if (isset($this->request->get['filter_logcenter'])) {
			$filter_logcenter = $this->request->get['filter_logcenter'];
		} else {
			$filter_logcenter = null;
		}

		if (isset($this->request->get['filter_recommended_code'])) {
			$filter_recommended_code = (string)$this->request->get['filter_recommended_code'];
		} else {
			$filter_recommended_code = null;
		}

        if (isset($this->request->get['filter_product_code'])) {//订单包含商品（仅限唯一码）
            $filter_product_code = $this->request->get['filter_product_code'];
        } else {
            $filter_product_code = null;
        }

		if (isset($this->request->get['sort'])) {
			$sort = $this->request->get['sort'];
		} else {
			$sort = 'o.date_added';
		}

		if (isset($this->request->get['order'])) {
			$order = $this->request->get['order'];
		} else {
			$order = 'DESC';
		}

		if (isset($this->request->get['page'])) {
			$page = $this->request->get['page'];
		} else {
			$page = 1;
		}

		$url = '';

		if (isset($this->request->get['filter_order_id'])) {
			$url .= '&filter_order_id=' . $this->request->get['filter_order_id'];
		}

		if (isset($this->request->get['filter_is_pay'])) {
			$url .= '&filter_is_pay=' . $this->request->get['filter_is_pay'];
		}

		if (isset($this->request->get['filter_is_shelf_order'])) {
			$url .= '&filter_is_shelf_order=' . $this->request->get['filter_is_shelf_order'];
		}

		if (isset($this->request->get['filter_customer'])) {
			$url .= '&filter_customer=' . urlencode(html_entity_decode($this->request->get['filter_customer'], ENT_QUOTES, 'UTF-8'));
		}

		if (isset($this->request->get['filter_order_status'])) {
			$url .= '&filter_order_status=' . $this->request->get['filter_order_status'];
		}

		if (isset($this->request->get['filter_verify_status'])) {
			$url .= '&filter_verify_status=' . $this->request->get['filter_verify_status'];
		}

		if (isset($this->request->get['filter_total'])) {
			$url .= '&filter_total=' . $this->request->get['filter_total'];
		}

		if (isset($this->request->get['filter_date_added'])) {
			$url .= '&filter_date_added=' . $this->request->get['filter_date_added'];
		}

		if (isset($this->request->get['filter_date_start'])) {
			$url .= '&filter_date_start=' . $this->request->get['filter_date_start'];
		}

		if (isset($this->request->get['filter_date_end'])) {
			$url .= '&filter_date_end=' . $this->request->get['filter_date_end'];
		}

		if (isset($this->request->get['filter_date_modified'])) {
			$url .= '&filter_date_modified=' . $this->request->get['filter_date_modified'];
		}
		if (isset($this->request->get['is_shelf_order'])) {
			$url .= '&is_shelf_order=' . $this->request->get['is_shelf_order'];
		}

		if (isset($this->request->get['filter_logcenter'])) {
			$url .= '&filter_logcenter=' . $this->request->get['filter_logcenter'];
		}

		if (isset($this->request->get['filter_recommended_code'])) {
			$url .= '&filter_recommended_code=' . (string)$this->request->get['filter_recommended_code'];
		}

        if (isset($this->request->get['filter_product_code'])) {//订单包含商品（仅限唯一码）
            $url .= '&filter_product_code=' . (string)$this->request->get['filter_product_code'];
        }

		if (isset($this->request->get['sort'])) {
			$url .= '&sort=' . $this->request->get['sort'];
		}

		if (isset($this->request->get['order'])) {
			$url .= '&order=' . $this->request->get['order'];
		}
/*
		if (isset($this->request->get['page'])) {
			$url .= '&page=' . $this->request->get['page'];
		}
*/
		$data['breadcrumbs'] = array();

		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('text_home'),
			'href' => $this->url->link('common/dashboard', 'token=' . $this->session->data['token'], 'SSL')
		);

		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('heading_title'),
			'href' => $this->url->link('sale/order', 'token=' . $this->session->data['token'] . $url, 'SSL')
		);

		$data['invoice'] = $this->url->link('sale/order/invoice', 'token=' . $this->session->data['token'], 'SSL');
		$data['shipping'] = $this->url->link('sale/order/shipping', 'token=' . $this->session->data['token'], 'SSL');
		$data['add'] = $this->url->link('sale/order/add', 'token=' . $this->session->data['token'], 'SSL');
		$data['exportReceiptWithOutPay'] = $this->url->link('sale/order/exportReceiptWithOutPay', 'token=' . $this->session->data['token'], 'SSL');

		$data['orders'] = array();

		$filter_data = array(
			'filter_order_id'      => $filter_order_id,
			'filter_is_pay'		   => $filter_is_pay,
			'filter_is_shelf_order'		   => $filter_is_shelf_order,
			'filter_customer'	   => $filter_customer,
			'filter_order_status'  => $filter_order_status,
			'filter_total'         => $filter_total,
			'filter_verify_status' => $filter_verify_status,
			'filter_date_added'    => $filter_date_added,
			'filter_date_modified' => $filter_date_modified,
			'filter_logcenter' 	   => $filter_logcenter,
			'filter_date_start'	   => $filter_date_start,
			'filter_date_end'	   => $filter_date_end,
			'filter_recommended_code'=> $filter_recommended_code,
            'filter_product_code'  => $filter_product_code,
			'sort'                 => $sort,
			'order'                => $order,
			'start'                => ($page - 1) * $this->config->get('config_limit_admin'),
			'limit'                => $this->config->get('config_limit_admin')
		);
		$order_total = $this->model_sale_order->getTotalOrders($filter_data);

		$results = $this->model_sale_order->getOrders($filter_data);
        //订单的时间点更新有问题，直接获取基于订单编号的出库单相关时间，入库单最晚创建时间和入库单最晚签收时间
        $soList = $this->model_sale_stock_out->getDateRangeGroupByOrderId();

		$data['array_is_pay'] = array(
			'3' =>'',
			'0' =>'未付款',
			'1'	=> '已付款',
			);
		$data['array_is_shelf_order'] = array(
			'3' =>'',
			'0' =>'否',
			'1'	=> '是',
			);
		$bill_array = array(
			'1'=>'未开发票',
			'2'=>'已开发票',
			'0'=>'不需要开发票',
			);
		$status_color = array(
			'5' => 'green',
			'2'	=> 'red',
			'17'=> '#FA0',
			'18'=> 'blue',
			);
		 // var_dump($results);die;
		foreach ($results as $result) {
            $firstCtaDayTimes = '<strong style="color:blue;">'.floor((time()-strtotime($result['date_added']))/86400).'</strong>';
            $lastCtaDayTimes = '';
            $firstCtcDayTimes = '';
            $lastCtcDayTimes = '';
            if (array_key_exists($result['order_id'], $soList)) {
                $firstCtaDayTimes = floor((strtotime($soList[$result['order_id']]['firstDateAdded'])-strtotime($result['date_added']))/86400);
                if ($firstCtaDayTimes >= 3){
                    $firstCtaDayTimes = '<strong style="color:red;">'.$firstCtaDayTimes.'</strong>';
                }else{
                    $firstCtaDayTimes = '<strong style="color:green;">'.$firstCtaDayTimes.'</strong>';
                }

                $lastCtaDayTimes = floor((strtotime($soList[$result['order_id']]['lastDateAdded'])-strtotime($result['date_added']))/86400);
                if ($lastCtaDayTimes >= 3){
                    $lastCtaDayTimes = '<strong style="color:red;">'.$lastCtaDayTimes.'</strong>';
                }else{
                    $lastCtaDayTimes = '<strong style="color:green;">'.$lastCtaDayTimes.'</strong>';
                }

                if ($soList[$result['order_id']]['firstReceiveDate']) {
                    $firstCtcDayTimes = floor((strtotime($soList[$result['order_id']]['firstReceiveDate'])-strtotime($result['date_added']))/86400);
                }

                if ($soList[$result['order_id']]['lastReceiveDate']) {
                    $lastCtcDayTimes = floor((strtotime($soList[$result['order_id']]['lastReceiveDate'])-strtotime($result['date_added']))/86400);
                }
            }
            $refundInfo = $this->model_sale_order->getOnlineRefundInfo($result['order_id']);
			$data['orders'][] = array(
				'order_id'      => $result['order_id'],
				'shipping_company'=> $result['shipping_company'],
				'difference'	=> $result['difference'],
				'customer'      => $result['customer'],
				'verify_status' => intval($result['verify_status'])?(intval($result['verify_status'])==1?'已审核(缺货)':'已审核'):'未审核',
				'status'        => $result['status'],
				'order_status_id'=> $result['order_status_id'],
				//'all_color'     => $this->model_sale_order->checkOrderDate($result['date_added'],$result['order_status_id']),//状态不等于18或5，并且下单超过5天的显示为红色shelf_order_id
				'all_color'     => 'black',
				'payment_method'=> $result['payment_method'],
				'shelf_order_id'=> $result['shelf_order_id'],
				'is_shelf_order'=> $result['shelf_order_id']?'是':'否',
				'is_pay'		=> $result['is_pay']?'已付款':'未付款',
				'status_color'	=> $status_color[$result['order_status_id']],
				'shipping_zone' => $result['shipping_zone'],
				'sign_price' => $result['sign_price'],
				'shipping_country'=>$result['shipping_country'],
				'recommended_code'=>$result['recommended_code'],
				'bill_status'	=> $bill_array[$result['bill_status']],
				'total'         => $this->currency->format($result['total'], $result['currency_code'], $result['currency_value']),
				'ori_total'     => $this->currency->format($result['ori_total'], $result['currency_code'], $result['currency_value']),
				'date_added'    => date('Y-m-d H:i', strtotime($result['date_added'])),
				'date_modified' => date($this->language->get('date_format_short'), strtotime($result['date_modified'])),
                'first_cta_day_times' => $firstCtaDayTimes,
                'last_cta_day_times' => $lastCtaDayTimes,
                'first_ctc_day_times' => $firstCtcDayTimes,
                'last_ctc_day_times' => $lastCtcDayTimes,
				'recommended_name'=> $result['recommended_name'],
				'shipping_code' => $result['shipping_code'],
				'logcenter_name'=>$result['logcenter_name'],
				'hang_status' => $result['hang_status'],
				'total_percant' => $result['total_percant']?$result['total_percant'].'%':'',
				'remark' => $result['comment'],
                'unAppliedRefundInfo' => $refundInfo['unApplied'],
                'appliedRefundInfo' => $refundInfo['applied'],

				'auditted_time'         => $soList[$result['order_id']]['firstDateAdded'],//$result['auditted_time'],//审核时间
				'out_time'              => $soList[$result['order_id']]['firstOutDate'],//$result['out_time'],//出库时间
				'delivered_time'        => $soList[$result['order_id']]['firstDeliverDate'],//$result['delivered_time'],//派送时间
				'completed_time'        => ($result['completed_time'])?$soList[$result['order_id']]['firstDateReceive']:'',//$result['completed_time'],//完成时间

                /*
                'stockOutRateByType' => $result['stock_out_rate_by_type'],
                'stockOutRateByQty' => $result['stock_out_rate_by_qty'],
                'stockOutRateByPrice' => $result['stock_out_rate_by_price'],
                'deliveryRateByType' => $result['delivery_rate_by_type'],
                'deliveryRateByQty' => $result['delivery_rate_by_qty'],
                'deliveryRateByPrice' => $result['delivery_rate_by_price'],
                */
				'view'          => $this->url->link('sale/order/info', 'token=' . $this->session->data['token'] . '&order_id=' . $result['order_id'] . $url, 'SSL'),
				'edit'          => $this->url->link('sale/order/edit', 'token=' . $this->session->data['token'] . '&order_id=' . $result['order_id'] . $url, 'SSL'),
			);
		}

		$data['heading_title'] = $this->language->get('heading_title');

		$data['text_list'] = $this->language->get('text_list');
		$data['text_no_results'] = $this->language->get('text_no_results');
		$data['text_confirm'] = $this->language->get('text_confirm');
		$data['text_missing'] = $this->language->get('text_missing');
		$data['text_loading'] = $this->language->get('text_loading');

		$data['column_order_id'] = $this->language->get('column_order_id');
		$data['column_customer'] = $this->language->get('column_customer');
		$data['column_status'] = $this->language->get('column_status');
		$data['column_total'] = $this->language->get('column_total');
		$data['column_date_added'] = $this->language->get('column_date_added');
		$data['column_date_modified'] = $this->language->get('column_date_modified');
		$data['column_action'] = $this->language->get('column_action');

		$data['entry_return_id'] = $this->language->get('entry_return_id');
		$data['entry_order_id'] = $this->language->get('entry_order_id');
		$data['entry_customer'] = $this->language->get('entry_customer');
		$data['entry_order_status'] = $this->language->get('entry_order_status');
		$data['entry_total'] = $this->language->get('entry_total');
		$data['entry_date_added'] = $this->language->get('entry_date_added');
		$data['entry_date_modified'] = $this->language->get('entry_date_modified');

		$data['button_invoice_print'] = $this->language->get('button_invoice_print');
		$data['button_shipping_print'] = $this->language->get('button_shipping_print');
		$data['button_add'] = $this->language->get('button_add');
		$data['button_edit'] = $this->language->get('button_edit');
		$data['button_delete'] = $this->language->get('button_delete');
		$data['button_filter'] = $this->language->get('button_filter');
		$data['button_view'] = $this->language->get('button_view');
		$data['button_ip_add'] = $this->language->get('button_ip_add');

		$data['token'] = $this->session->data['token'];
		$data['user_group_id'] = $this->session->data['user_group_id'];
		$data['user_id'] = $this->session->data['user_id'];

		if (isset($this->request->post['selected'])) {
			$data['selected'] = (array)$this->request->post['selected'];
		} else {
			$data['selected'] = array();
		}

		if (isset($this->session->data['error'])) {
			$data['error_warning'] = $this->session->data['error'];
			unset($this->session->data['error']);
		} elseif (isset($this->error['warning'])) {
			$data['error_warning'] = $this->error['warning'];
		} else {
			$data['error_warning'] = '';
		}
		$url = '';

		if (isset($this->request->get['filter_order_id'])) {
			$url .= '&filter_order_id=' . $this->request->get['filter_order_id'];
		}

		if (isset($this->request->get['filter_customer'])) {
			$url .= '&filter_customer=' . urlencode(html_entity_decode($this->request->get['filter_customer'], ENT_QUOTES, 'UTF-8'));
		}

		if (isset($this->request->get['filter_order_status'])) {
			$url .= '&filter_order_status=' . $this->request->get['filter_order_status'];
		}

		if (isset($this->request->get['filter_verify_status'])) {
			$url .= '&filter_verify_status=' . $this->request->get['filter_verify_status'];
		}

		if (isset($this->request->get['filter_total'])) {
			$url .= '&filter_total=' . $this->request->get['filter_total'];
		}

		if (isset($this->request->get['filter_date_added'])) {
			$url .= '&filter_date_added=' . $this->request->get['filter_date_added'];
		}

		if (isset($this->request->get['filter_date_modified'])) {
			$url .= '&filter_date_modified=' . $this->request->get['filter_date_modified'];
		}
		if (isset($this->request->get['filter_recommended_code'])) {
			$url .= '&filter_recommended_code=' . $this->request->get['filter_recommended_code'];
		}

        if (isset($this->request->get['filter_product_code'])) {//订单包含商品（仅限唯一码）
            $url .= '&filter_product_code=' . (string)$this->request->get['filter_product_code'];
        }

		if ($order == 'ASC') {
			$url .= '&order=DESC';
		} else {
			$url .= '&order=ASC';
		}

		if (isset($this->request->get['page'])) {
			$url .= '&page=' . $this->request->get['page'];
		}

        $data['hand_order'] = $this->url->link('sale/order/add', 'token=' . $this->session->data['token'] . $url, 'SSL');
		$data['sort_order'] = $this->url->link('sale/order', 'token=' . $this->session->data['token'] . '&sort=o.order_id' . $url, 'SSL');
		$data['sort_customer'] = $this->url->link('sale/order', 'token=' . $this->session->data['token'] . '&sort=customer' . $url, 'SSL');
		$data['sort_status'] = $this->url->link('sale/order', 'token=' . $this->session->data['token'] . '&sort=status' . $url, 'SSL');
		$data['sort_verify_status'] = $this->url->link('sale/order', 'token=' . $this->session->data['token'] . '&sort=verify_status' . $url, 'SSL');
		$data['sort_total'] = $this->url->link('sale/order', 'token=' . $this->session->data['token'] . '&sort=o.total' . $url, 'SSL');
		$data['sort_ori_total'] = $this->url->link('sale/order', 'token=' . $this->session->data['token'] . '&sort=o.ori_total' . $url, 'SSL');
		$data['sort_date_added'] = $this->url->link('sale/order', 'token=' . $this->session->data['token'] . '&sort=o.date_added' . $url, 'SSL');
		$data['sort_date_modified'] = $this->url->link('sale/order', 'token=' . $this->session->data['token'] . '&sort=o.date_modified' . $url, 'SSL');
        $data['sort_SOT'] = $this->url->link('sale/order', 'token=' . $this->session->data['token'] . '&sort=o.stock_out_rate_by_type' . $url, 'SSL');
        $data['sort_SOQ'] = $this->url->link('sale/order', 'token=' . $this->session->data['token'] . '&sort=o.stock_out_rate_by_qty' . $url, 'SSL');
        $data['sort_SOP'] = $this->url->link('sale/order', 'token=' . $this->session->data['token'] . '&sort=o.stock_out_rate_by_price' . $url, 'SSL');
        $data['sort_DT'] = $this->url->link('sale/order', 'token=' . $this->session->data['token'] . '&sort=o.delivery_rate_by_type' . $url, 'SSL');
        $data['sort_DQ'] = $this->url->link('sale/order', 'token=' . $this->session->data['token'] . '&sort=o.delivery_rate_by_qty' . $url, 'SSL');
        $data['sort_DT'] = $this->url->link('sale/order', 'token=' . $this->session->data['token'] . '&sort=o.delivery_rate_by_price' . $url, 'SSL');

		$url = '';

		if (isset($this->request->get['filter_order_id'])) {
			$url .= '&filter_order_id=' . $this->request->get['filter_order_id'];
		}

		if (isset($this->request->get['filter_is_pay'])) {
			$url .= '&filter_is_pay=' . $this->request->get['filter_is_pay'];
		}
		if (isset($this->request->get['filter_is_shelf_order'])) {
			$url .= '&filter_is_shelf_order=' . $this->request->get['filter_is_shelf_order'];
		}


		if (isset($this->request->get['filter_customer'])) {
			$url .= '&filter_customer=' . urlencode(html_entity_decode($this->request->get['filter_customer'], ENT_QUOTES, 'UTF-8'));
		}

		if (isset($this->request->get['filter_order_status'])) {
			$url .= '&filter_order_status=' . $this->request->get['filter_order_status'];
		}

		if (isset($this->request->get['filter_verify_status'])) {
			$url .= '&filter_verify_status=' . $this->request->get['filter_verify_status'];
		}

		if (isset($this->request->get['filter_recommended_code'])) {
			$url .= '&filter_recommended_code=' . $this->request->get['filter_recommended_code'];
		}

		if (isset($this->request->get['filter_total'])) {
			$url .= '&filter_total=' . $this->request->get['filter_total'];
		}

		if (isset($this->request->get['filter_date_added'])) {
			$url .= '&filter_date_added=' . $this->request->get['filter_date_added'];
		}

		if (isset($this->request->get['filter_date_modified'])) {
			$url .= '&filter_date_modified=' . $this->request->get['filter_date_modified'];
		}

        if (isset($this->request->get['filter_product_code'])) {//订单包含商品（仅限唯一码）
            $url .= '&filter_product_code=' . (string)$this->request->get['filter_product_code'];
        }

		if (isset($this->request->get['sort'])) {
			$url .= '&sort=' . $this->request->get['sort'];
		}

		if (isset($this->request->get['order'])) {
			$url .= '&order=' . $this->request->get['order'];
		}

		$pagination = new Pagination();
		$pagination->total = $order_total;
		$pagination->page = $page;
		$pagination->limit = $this->config->get('config_limit_admin');
		$pagination->url = $this->url->link('sale/order', 'token=' . $this->session->data['token'] . $url . '&page={page}', 'SSL');

		$data['pagination'] = $pagination->render();

		$data['results'] = sprintf($this->language->get('text_pagination'), ($order_total) ? (($page - 1) * $this->config->get('config_limit_admin')) + 1 : 0, ((($page - 1) * $this->config->get('config_limit_admin')) > ($order_total - $this->config->get('config_limit_admin'))) ? $order_total : ((($page - 1) * $this->config->get('config_limit_admin')) + $this->config->get('config_limit_admin')), $order_total, ceil($order_total / $this->config->get('config_limit_admin')));

		$data['filter_order_id'] = $filter_order_id;
		$data['filter_customer'] = $filter_customer;
		$data['filter_is_pay'] = $filter_is_pay;
		$data['filter_is_shelf_order'] = $filter_is_shelf_order;
		$data['filter_order_status'] = $filter_order_status;
		$data['filter_total'] = $filter_total;
		$data['filter_date_added'] = $filter_date_added;
		$data['filter_date_modified'] = $filter_date_modified;
		$data['filter_date_start'] = $filter_date_start;
		$data['filter_date_end'] = $filter_date_end;
		$data['filter_recommended_code'] = $filter_recommended_code;
        $data['filter_product_code'] = $filter_product_code;//订单包含商品（仅限唯一码）

		$this->load->model('localisation/order_status');

		$data['filter_verify_status'] = $filter_verify_status;
		$data['order_statuses'] = $this->model_localisation_order_status->getOrderStatuses();

		$data['sort'] = $sort;
		$data['order'] = $order;
		$data['orderClass'] = ($order == 'DESC')?'ASC':'DESC';

		$data['store'] = HTTPS_CATALOG;

		// API login
		$this->load->model('user/api');

		$api_info = $this->model_user_api->getApi($this->config->get('config_api_id'));

		if ($api_info) {
			$data['api_id'] = $api_info['api_id'];
			$data['api_key'] = $api_info['key'];
			$data['api_ip'] = $this->request->server['REMOTE_ADDR'];
		} else {
			$data['api_id'] = '';
			$data['api_key'] = '';
			$data['api_ip'] = '';
		}

		$data['can_edit'] = $this->user->hasPermission('modify', 'sale/order');

		$data['header'] = $this->load->controller('common/header');
		$data['column_left'] = $this->load->controller('common/column_left');
		$data['footer'] = $this->load->controller('common/footer');
		$data['user_id'] = $this->user->getId();
		$this->response->setOutput($this->load->view('sale/order_list.tpl', $data));
	}

	public function getForm() {
		$this->load->model('customer/customer');

		$data['heading_title'] = $this->language->get('heading_title');

		$data['text_form'] = !isset($this->request->get['order_id']) ? $this->language->get('text_add') : $this->language->get('text_edit');
		$data['text_no_results'] = $this->language->get('text_no_results');
		$data['text_default'] = $this->language->get('text_default');
		$data['text_select'] = $this->language->get('text_select');
		$data['text_none'] = $this->language->get('text_none');
		$data['text_loading'] = $this->language->get('text_loading');
		$data['text_ip_add'] = sprintf($this->language->get('text_ip_add'), $this->request->server['REMOTE_ADDR']);
		$data['text_product'] = $this->language->get('text_product');
		$data['text_voucher'] = $this->language->get('text_voucher');
		$data['text_order_detail'] = $this->language->get('text_order_detail');

		$data['entry_store'] = $this->language->get('entry_store');
		$data['entry_customer'] = $this->language->get('entry_customer');
		$data['entry_customer_group'] = $this->language->get('entry_customer_group');
		$data['entry_fullname'] = $this->language->get('entry_fullname');
		$data['entry_email'] = $this->language->get('entry_email');
		$data['entry_telephone'] = $this->language->get('entry_telephone');
		$data['entry_shipping_telephone'] = $this->language->get('entry_shipping_telephone');
		$data['entry_fax'] = $this->language->get('entry_fax');
		$data['entry_comment'] = $this->language->get('entry_comment');
		$data['entry_affiliate'] = $this->language->get('entry_affiliate');
		$data['entry_address'] = $this->language->get('entry_address');
		$data['entry_company'] = $this->language->get('entry_company');
		$data['entry_address'] = $this->language->get('entry_address');
		$data['entry_city'] = $this->language->get('entry_city');
		$data['entry_postcode'] = $this->language->get('entry_postcode');
		$data['entry_zone'] = $this->language->get('entry_zone');
		$data['entry_zone_code'] = $this->language->get('entry_zone_code');
		$data['entry_country'] = $this->language->get('entry_country');
		$data['entry_product'] = $this->language->get('entry_product');
		$data['entry_option'] = $this->language->get('entry_option');
		$data['entry_quantity'] = $this->language->get('entry_quantity');
		$data['entry_to_name'] = $this->language->get('entry_to_name');
		$data['entry_to_email'] = $this->language->get('entry_to_email');
		$data['entry_from_name'] = $this->language->get('entry_from_name');
		$data['entry_from_email'] = $this->language->get('entry_from_email');
		$data['entry_theme'] = $this->language->get('entry_theme');
		$data['entry_message'] = $this->language->get('entry_message');
		$data['entry_amount'] = $this->language->get('entry_amount');
		$data['entry_currency'] = $this->language->get('entry_currency');
		$data['entry_shipping_method'] = $this->language->get('entry_shipping_method');
		$data['entry_payment_method'] = $this->language->get('entry_payment_method');
		$data['entry_coupon'] = $this->language->get('entry_coupon');
		$data['entry_voucher'] = $this->language->get('entry_voucher');
		$data['entry_reward'] = $this->language->get('entry_reward');
		$data['entry_order_status'] = $this->language->get('entry_order_status');

		$data['column_product'] = $this->language->get('column_product');
		$data['column_model'] = $this->language->get('column_model');
		$data['column_quantity'] = $this->language->get('column_quantity');
		$data['column_price'] = $this->language->get('column_price');
		$data['column_total'] = $this->language->get('column_total');
		$data['column_action'] = $this->language->get('column_action');

		$data['button_save'] = $this->language->get('button_save');
		$data['button_cancel'] = $this->language->get('button_cancel');
		$data['button_continue'] = $this->language->get('button_continue');
		$data['button_back'] = $this->language->get('button_back');
		$data['button_refresh'] = $this->language->get('button_refresh');
		$data['button_product_add'] = $this->language->get('button_product_add');
		$data['button_voucher_add'] = $this->language->get('button_voucher_add');
		$data['button_apply'] = $this->language->get('button_apply');
		$data['button_upload'] = $this->language->get('button_upload');
		$data['button_remove'] = $this->language->get('button_remove');
		$data['button_ip_add'] = $this->language->get('button_ip_add');

		$data['tab_order'] = $this->language->get('tab_order');
		$data['tab_customer'] = $this->language->get('tab_customer');
		$data['tab_payment'] = $this->language->get('tab_payment');
		$data['tab_shipping'] = $this->language->get('tab_shipping');
		$data['tab_product'] = $this->language->get('tab_product');
		$data['tab_voucher'] = $this->language->get('tab_voucher');
		$data['tab_total'] = $this->language->get('tab_total');

		$data['token'] = $this->session->data['token'];

		$url = '';

		if (isset($this->request->get['filter_order_id'])) {
			$url .= '&filter_order_id=' . $this->request->get['filter_order_id'];
		}

		if (isset($this->request->get['filter_customer'])) {
			$url .= '&filter_customer=' . urlencode(html_entity_decode($this->request->get['filter_customer'], ENT_QUOTES, 'UTF-8'));
		}

		if (isset($this->request->get['filter_order_status'])) {
			$url .= '&filter_order_status=' . $this->request->get['filter_order_status'];
		}

		if (isset($this->request->get['filter_total'])) {
			$url .= '&filter_total=' . $this->request->get['filter_total'];
		}

		if (isset($this->request->get['filter_date_added'])) {
			$url .= '&filter_date_added=' . $this->request->get['filter_date_added'];
		}

		if (isset($this->request->get['filter_date_modified'])) {
			$url .= '&filter_date_modified=' . $this->request->get['filter_date_modified'];
		}

		if (isset($this->request->get['sort'])) {
			$url .= '&sort=' . $this->request->get['sort'];
		}

		if (isset($this->request->get['order'])) {
			$url .= '&order=' . $this->request->get['order'];
		}

		if (isset($this->request->get['page'])) {
			$url .= '&page=' . $this->request->get['page'];
		}

		$data['breadcrumbs'] = array();

		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('text_home'),
			'href' => $this->url->link('common/dashboard', 'token=' . $this->session->data['token'], 'SSL')
		);

		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('heading_title'),
			'href' => $this->url->link('sale/order', 'token=' . $this->session->data['token'] . $url, 'SSL')
		);

		$data['cancel'] = $this->url->link('sale/order', 'token=' . $this->session->data['token'] . $url, 'SSL');

		if (isset($this->request->get['order_id'])) {
			$order_info = $this->model_sale_order->getOrder($this->request->get['order_id']);
		}

		if (!empty($order_info)) {
			$data['order_id'] = $this->request->get['order_id'];
			$data['store_id'] = $order_info['store_id'];

			$data['customer'] = $order_info['customer'];
			$data['customer_id'] = $order_info['customer_id'];
			$data['customer_group_id'] = $order_info['customer_group_id'];
			$data['fullname'] = $order_info['fullname'];
			$data['email'] = $order_info['email'];
			$data['telephone'] = $order_info['telephone'];
			$data['fax'] = $order_info['fax'];
			$data['account_custom_field'] = $order_info['custom_field'];

			$this->load->model('customer/customer');

			$data['addresses'] = $this->model_customer_customer->getAddresses($order_info['customer_id']);

			$data['payment_fullname'] = $order_info['payment_fullname'];
			$data['payment_company'] = $order_info['payment_company'];
			$data['payment_address'] = $order_info['payment_address'];
			$data['payment_city'] = $order_info['payment_city'];
			$data['payment_city_id'] = $order_info['payment_city_id'];
			$data['payment_postcode'] = $order_info['payment_postcode'];
			$data['payment_country_id'] = $order_info['payment_country_id'];
			$data['payment_zone_id'] = $order_info['payment_zone_id'];
			$data['payment_custom_field'] = $order_info['payment_custom_field'];
			$data['payment_method'] = $order_info['payment_method'];
			$data['payment_code'] = $order_info['payment_code'];

			$data['shipping_fullname'] = $order_info['shipping_fullname'];
			$data['shipping_telephone'] = $order_info['shipping_telephone'];
			$data['shipping_company'] = $order_info['shipping_company'];
			$data['shipping_address'] = $order_info['shipping_address'];
			$data['shipping_city'] = $order_info['shipping_city'];
			$data['shipping_city_id'] = $order_info['shipping_city_id'];
			$data['shipping_postcode'] = $order_info['shipping_postcode'];
			$data['shipping_country_id'] = $order_info['shipping_country_id'];
			$data['shipping_zone_id'] = $order_info['shipping_zone_id'];
			$data['shipping_custom_field'] = $order_info['shipping_custom_field'];
			$data['shipping_method'] = $order_info['shipping_method'];
			$data['shipping_code'] = $order_info['shipping_code'];

			// Products
			$data['order_products'] = array();

			$products = $this->model_sale_order->getOrderProducts($this->request->get['order_id']);

			foreach ($products as $product) {
				$data['order_products'][] = array(
					'product_id' => $product['product_id'],
					'name'       => $product['name'],
					'model'      => $product['model'],
					'option'     => $this->model_sale_order->getOrderOptions($this->request->get['order_id'], $product['order_product_id']),
					'quantity'   => $product['quantity'],
					'price'      => $product['price'],
					'total'      => $product['total'],
					'reward'     => $product['reward']
				);
			}

			// Vouchers
			$data['order_vouchers'] = $this->model_sale_order->getOrderVouchers($this->request->get['order_id']);

			$data['coupon'] = '';
			$data['voucher'] = '';
			$data['reward'] = '';

			$data['order_totals'] = array();

			$order_totals = $this->model_sale_order->getOrderTotals($this->request->get['order_id']);

			foreach ($order_totals as $order_total) {
				// If coupon, voucher or reward points
				$start = strpos($order_total['title'], '(') + 1;
				$end = strrpos($order_total['title'], ')');

				if ($start && $end) {
					$data[$order_total['code']] = substr($order_total['title'], $start, $end - $start);
				}
			}

			$data['order_status_id'] = $order_info['order_status_id'];
			$data['comment'] = $order_info['comment'];
			$data['affiliate_id'] = $order_info['affiliate_id'];
			$data['affiliate'] = $order_info['affiliate_fullname'];
			$data['currency_code'] = $order_info['currency_code'];
		} else {
			$data['order_id'] = 0;
			$data['store_id'] = '';
			$data['customer'] = '';
			$data['customer_id'] = '';
			$data['customer_group_id'] = $this->config->get('config_customer_group_id');
			$data['fullname'] = '';
			$data['email'] = '';
			$data['telephone'] = '';
			$data['fax'] = '';
			$data['customer_custom_field'] = array();

			$data['addresses'] = array();

			$data['payment_fullname'] = '';
			$data['payment_company'] = '';
			$data['payment_address'] = '';
			$data['payment_city'] = '';
			$data['payment_city_id'] = '';
			$data['payment_postcode'] = '';
			$data['payment_country_id'] = '';
			$data['payment_zone_id'] = '';
			$data['payment_custom_field'] = array();
			$data['payment_method'] = '';
			$data['payment_code'] = '';

			$data['shipping_fullname'] = '';
			$data['shipping_telephone'] = '';
			$data['shipping_company'] = '';
			$data['shipping_address'] = '';
			$data['shipping_city'] = '';
			$data['shipping_city_id'] = '';
			$data['shipping_postcode'] = '';
			$data['shipping_country_id'] = '';
			$data['shipping_zone_id'] = '';
			$data['shipping_custom_field'] = array();
			$data['shipping_method'] = '';
			$data['shipping_code'] = '';

			$data['order_products'] = array();
			$data['order_vouchers'] = array();
			$data['order_totals'] = array();

			$data['order_status_id'] = $this->config->get('config_order_status_id');
			$data['comment'] = '';
			$data['affiliate_id'] = '';
			$data['affiliate'] = '';
			$data['currency_code'] = $this->config->get('config_currency');

			$data['coupon'] = '';
			$data['voucher'] = '';
			$data['reward'] = '';
		}

		// Stores
		$this->load->model('setting/store');

		$data['stores'] = array();

		$data['stores'][] = array(
			'store_id' => 0,
			'name'     => $this->language->get('text_default'),
			'href'     => HTTP_CATALOG
		);

		$results = $this->model_setting_store->getStores();


		foreach ($results as $result) {
			$data['stores'][] = array(
				'store_id' => $result['store_id'],
				'name'     => $result['name'],
				'href'     => $result['url']
			);
		}









		// Customer Groups
		$this->load->model('customer/customer_group');

		$data['customer_groups'] = $this->model_customer_customer_group->getCustomerGroups();

		// Custom Fields
		$this->load->model('customer/custom_field');

		$data['custom_fields'] = array();

		$filter_data = array(
			'sort'  => 'cf.sort_order',
			'order' => 'ASC'
		);

		$custom_fields = $this->model_customer_custom_field->getCustomFields($filter_data);

		foreach ($custom_fields as $custom_field) {
			$data['custom_fields'][] = array(
				'custom_field_id'    => $custom_field['custom_field_id'],
				'custom_field_value' => $this->model_customer_custom_field->getCustomFieldValues($custom_field['custom_field_id']),
				'name'               => $custom_field['name'],
				'value'              => $custom_field['value'],
				'type'               => $custom_field['type'],
				'location'           => $custom_field['location'],
				'sort_order'         => $custom_field['sort_order']
			);
		}

		$this->load->model('localisation/order_status');

		$data['order_statuses'] = $this->model_localisation_order_status->getOrderStatuses();

		$this->load->model('localisation/country');

		$data['countries'] = $this->model_localisation_country->getCountries();

		$this->load->model('localisation/currency');

		$data['currencies'] = $this->model_localisation_currency->getCurrencies();

		$data['voucher_min'] = $this->config->get('config_voucher_min');

		$this->load->model('sale/voucher_theme');

		$data['voucher_themes'] = $this->model_sale_voucher_theme->getVoucherThemes();


		// API login
		$this->load->model('user/api');

		$api_info = $this->model_user_api->getApi($this->config->get('config_api_id'));

		if ($api_info) {
			$data['api_id'] = $api_info['api_id'];
			$data['api_key'] = $api_info['key'];
			$data['api_ip'] = $this->request->server['REMOTE_ADDR'];
		} else {
			$data['api_id'] = '';
			$data['api_key'] = '';
			$data['api_ip'] = '';
		}


		$data['header'] = $this->load->controller('common/header');
		$data['column_left'] = $this->load->controller('common/column_left');
		$data['footer'] = $this->load->controller('common/footer');

		$this->response->setOutput($this->load->view('sale/order_form.tpl', $data));
	}

	public function info() {
		$this->load->model('sale/order');

		if (isset($this->request->get['order_id'])) {
			$order_id = $this->request->get['order_id'];
		} else {
			$order_id = 0;
		}

		$order_info = $this->model_sale_order->getOrder($order_id);
		if ($order_info) {
			$this->load->language('sale/order');

			$this->document->setTitle($this->language->get('heading_title'));

			$data['heading_title'] = $this->language->get('heading_title');

			$data['text_ip_add'] = sprintf($this->language->get('text_ip_add'), $this->request->server['REMOTE_ADDR']);
			$data['text_order_detail'] = $this->language->get('text_order_detail');
			$data['text_customer_detail'] = $this->language->get('text_customer_detail');
			$data['text_option'] = $this->language->get('text_option');
			$data['text_store'] = $this->language->get('text_store');
			$data['text_date_added'] = $this->language->get('text_date_added');
			$data['text_payment_method'] = $this->language->get('text_payment_method');
			$data['text_shipping_method'] = $this->language->get('text_shipping_method');
			$data['text_customer'] = $this->language->get('text_customer');
			$data['text_customer_group'] = $this->language->get('text_customer_group');
			$data['text_email'] = $this->language->get('text_email');
			$data['text_telephone'] = $this->language->get('text_telephone');
			$data['text_is_invoice_added'] = $this->language->get('text_is_invoice_added');
			$data['text_is_invoice_removed'] = $this->language->get('text_is_invoice_removed');
			$data['text_is_invoice_passed'] = $this->language->get('text_is_invoice_passed');
			$data['text_invoice'] = $this->language->get('text_invoice');
			$data['text_is_invoice'] = $this->language->get('text_is_invoice');
			$data['text_reward'] = $this->language->get('text_reward');
			$data['text_affiliate'] = $this->language->get('text_affiliate');
			$data['text_order'] = sprintf($this->language->get('text_order'), $this->request->get['order_id']);
			$data['text_payment_address'] = $this->language->get('text_payment_address');
			$data['text_shipping_address'] = $this->language->get('text_shipping_address');
			$data['text_comment'] = $this->language->get('text_comment');

			$data['text_account_custom_field'] = $this->language->get('text_account_custom_field');
			$data['text_payment_custom_field'] = $this->language->get('text_payment_custom_field');
			$data['text_shipping_custom_field'] = $this->language->get('text_shipping_custom_field');
			$data['text_browser'] = $this->language->get('text_browser');
			$data['text_ip'] = $this->language->get('text_ip');
			$data['text_forwarded_ip'] = $this->language->get('text_forwarded_ip');
			$data['text_user_agent'] = $this->language->get('text_user_agent');
			$data['text_accept_language'] = $this->language->get('text_accept_language');

			$data['text_history'] = $this->language->get('text_history');
			$data['text_history_add'] = $this->language->get('text_history_add');
			$data['text_loading'] = $this->language->get('text_loading');
			$data['text_shipping_telephone'] = $this->language->get('text_shipping_telephone');

			$data['column_sku'] = $this->language->get('column_sku');
			$data['column_product'] = $this->language->get('column_product');
			$data['column_model'] = $this->language->get('column_model');
			$data['column_quantity'] = $this->language->get('column_quantity');
			$data['column_price'] = $this->language->get('column_price');
			$data['column_total'] = $this->language->get('column_total');

			$data['entry_order_status'] = $this->language->get('entry_order_status');
			$data['entry_notify'] = $this->language->get('entry_notify');
			$data['entry_override'] = $this->language->get('entry_override');
			$data['entry_comment'] = $this->language->get('entry_comment');

			$data['entry_sent_comment_to_all'] = $this->language->get('entry_sent_comment_to_all');
			$data['help_sent_comment_to_all'] = $this->language->get('help_sent_comment_to_all');

			$data['help_override'] = $this->language->get('help_override');

			$data['button_invoice_print'] = $this->language->get('button_invoice_print');
			$data['button_shipping_print'] = $this->language->get('button_shipping_print');
			$data['button_edit'] = $this->language->get('button_edit');
			$data['button_cancel'] = $this->language->get('button_cancel');
			$data['button_generate'] = $this->language->get('button_generate');
			$data['button_is_invoice_add'] = $this->language->get('button_is_invoice_add');
			$data['button_is_invoice_remove'] = $this->language->get('button_is_invoice_remove');
			$data['button_reward_add'] = $this->language->get('button_reward_add');
			$data['button_reward_remove'] = $this->language->get('button_reward_remove');
			$data['button_commission_add'] = $this->language->get('button_commission_add');
			$data['button_commission_remove'] = $this->language->get('button_commission_remove');
			$data['button_history_add'] = $this->language->get('button_history_add');
			$data['button_ip_add'] = $this->language->get('button_ip_add');

			$data['tab_history'] = $this->language->get('tab_history');
			$data['tab_additional'] = $this->language->get('tab_additional');

			$data['token'] = $this->session->data['token'];
			$data['user_id'] = $this->user->getId();
			$data['user_name'] = $this->user->getUserName();

			$url = '';

			if (isset($this->request->get['filter_order_id'])) {
				$url .= '&filter_order_id=' . $this->request->get['filter_order_id'];
			}

			if (isset($this->request->get['filter_customer'])) {
				$url .= '&filter_customer=' . urlencode(html_entity_decode($this->request->get['filter_customer'], ENT_QUOTES, 'UTF-8'));
			}

			if (isset($this->request->get['filter_order_status'])) {
				$url .= '&filter_order_status=' . $this->request->get['filter_order_status'];
			}

			if (isset($this->request->get['filter_total'])) {
				$url .= '&filter_total=' . $this->request->get['filter_total'];
			}

			if (isset($this->request->get['filter_date_added'])) {
				$url .= '&filter_date_added=' . $this->request->get['filter_date_added'];
			}

			if (isset($this->request->get['filter_date_modified'])) {
				$url .= '&filter_date_modified=' . $this->request->get['filter_date_modified'];
			}

			if (isset($this->request->get['sort'])) {
				$url .= '&sort=' . $this->request->get['sort'];
			}

			if (isset($this->request->get['order'])) {
				$url .= '&order=' . $this->request->get['order'];
			}

			if (isset($this->request->get['page'])) {
				$url .= '&page=' . $this->request->get['page'];
			}

			$data['breadcrumbs'] = array();

			$data['breadcrumbs'][] = array(
				'text' => $this->language->get('text_home'),
				'href' => $this->url->link('common/dashboard', 'token=' . $this->session->data['token'], 'SSL')
			);

			$data['breadcrumbs'][] = array(
				'text' => $this->language->get('heading_title'),
				'href' => $this->url->link('sale/order', 'token=' . $this->session->data['token'] . $url, 'SSL')
			);

			$data['stock_out_data'] = $this->model_sale_order->getstockoutbyreferid($order_id);

			foreach($data['stock_out_data'] as $key=>$val){
				$data['stock_out_data'][$key]['url'] = $this->url->link('sale/stock_out/view', 'token=' . $this->session->data['token'] . '&out_id=' . $val['out_id'], 'SSL');
			}

			$data['export'] = $this->url->link('sale/order/export', 'token=' . $this->session->data['token'] . '&order_id=' . (int)$this->request->get['order_id'], 'SSL');
			$data['shipping'] = $this->url->link('sale/order/shipping', 'token=' . $this->session->data['token'] . '&order_id=' . (int)$this->request->get['order_id'], 'SSL');
			$data['invoice'] = $this->url->link('sale/order/invoice', 'token=' . $this->session->data['token'] . '&order_id=' . (int)$this->request->get['order_id'], 'SSL');
			$data['export_order'] = $this->url->link('sale/order/exportOrderDetails', 'token=' . $this->session->data['token'] . '&order_id=' . (int)$this->request->get['order_id'], 'SSL');

			/*编辑订单不改订单号*/
			$data['edit_order'] = $this->url->link('sale/order/editOrder', 'token=' . $this->session->data['token'] . '&order_id=' . (int)$this->request->get['order_id'], 'SSL');
			/*编辑订单不改订单号*/

			$data['edit'] = $this->url->link('sale/order/edit', 'token=' . $this->session->data['token'] . '&order_id=' . (int)$this->request->get['order_id'], 'SSL');
			$data['cancel'] = $this->url->link('sale/order', 'token=' . $this->session->data['token'] . $url, 'SSL');

			$data['order_id'] = $this->request->get['order_id'];

			$data['store_name'] = $order_info['store_name'];
			$data['store_url'] = $order_info['store_url'];
			$data['sign_price'] = $order_info['sign_price'];
			$data['remarks'] = $order_info['remarks'];
			$data['conform_price'] = $order_info['conform_price'];

			if ($order_info['invoice_no']) {
				$data['invoice_no'] = $order_info['invoice_prefix'] . $order_info['invoice_no'];
			} else {
				$data['invoice_no'] = '';
			}


			$data['date_added'] = date($this->language->get('date_format_short'), strtotime($order_info['date_added']));
			$data['fullname'] = $order_info['fullname'];

			if ($order_info['customer_id']) {
				$data['customer'] = $this->url->link('customer/customer/edit', 'token=' . $this->session->data['token'] . '&customer_id=' . $order_info['customer_id'], 'SSL');
			} else {
				$data['customer'] = '';
			}

			$this->load->model('customer/customer_group');

			$customer_group_info = $this->model_customer_customer_group->getCustomerGroup($order_info['customer_group_id']);

			if ($customer_group_info) {
				$data['customer_group'] = $customer_group_info['name'];
			} else {
				$data['customer_group'] = '';
			}

			$data['email'] = $order_info['email'];
			$data['telephone'] = $order_info['telephone'];

			$data['is_pay'] = $order_info['is_pay']?'已付款':'未付款';

			$data['shipping_telephone'] = $order_info['shipping_telephone'];

			$data['shipping_method'] = $order_info['shipping_method'];
			$data['recommended_code'] = $order_info['recommended_code'];
			$data['payment_method'] = $order_info['payment_method'];

			// Payment Address
			if ($order_info['payment_address_format']) {
				$format = $order_info['payment_address_format'];
			} else {
				$format = '{fullname}' . "\n" . '{company}' . "\n" . '{address}' . "\n" . '{city} {postcode}' . "\n" . '{zone}' . "\n" . '{country}';
			}

			$find = array(
				'{fullname}',
				'{company}',
				'{address}',
				'{city}',
				'{postcode}',
				'{zone}',
				'{zone_code}',
				'{country}'
			);

			$replace = array(
				'fullname' 	=> $order_info['payment_fullname'],
				'company'   => $order_info['payment_company'],
				'address' 	=> $order_info['payment_address'],
				'city'      => $order_info['payment_city'],
				'postcode'  => $order_info['payment_postcode'],
				'zone'      => $order_info['payment_zone'],
				'zone_code' => $order_info['payment_zone_code'],
				'country'   => $order_info['payment_country']
			);

			$data['payment_address'] = str_replace(array("\r\n", "\r", "\n"), '<br />', preg_replace(array("/\s\s+/", "/\r\r+/", "/\n\n+/"), '<br />', trim(str_replace($find, $replace, $format))));

			// Shipping Address
			if ($order_info['shipping_address_format']) {
				$format = $order_info['shipping_address_format'];
			} else {
				$format = '{fullname}' . "\n" . '{company}' . "\n" . '{address}' . "\n" . '{city} {postcode}' . "\n" . '{zone}' . "\n" . '{country}';
			}

			$find = array(
				'{fullname}',
				'{company}',
				'{address}',
				'{city}',
				'{postcode}',
				'{zone}',
				'{zone_code}',
				'{country}'
			);

			$replace = array(
				'fullname' 	=> $order_info['shipping_fullname'],
				'company'   => $order_info['shipping_company'],
				'address' => $order_info['shipping_address'],
				'city'      => $order_info['shipping_city'],
				'postcode'  => $order_info['shipping_postcode'],
				'zone'      => $order_info['shipping_zone'],
				'zone_code' => $order_info['shipping_zone_code'],
				'country'   => $order_info['shipping_country']
			);

			$data['shipping_address'] = str_replace(array("\r\n", "\r", "\n"), '<br />', preg_replace(array("/\s\s+/", "/\r\r+/", "/\n\n+/"), '<br />', trim(str_replace($find, $replace, $format))));

			// Uploaded files
			$this->load->model('tool/upload');

			$data['products'] = array();

			$this->load->model('catalog/vendor');
			$products = $this->model_sale_order->getOrderProducts($this->request->get['order_id']);

			$total_ship_status = 1;
			foreach ($products as $product) {
				$option_data = array();

				$options = $this->model_sale_order->getOrderOptions($this->request->get['order_id'], $product['order_product_id']);

			$product_vendor_info = M('vendor')->where(array('vproduct_id'=>$product['product_id']))->field('vendor')->find();
	        if($product_vendor_info) {
	         $product['vendor_id'] = $product_vendor_info['vendor'];
	        }
				$vname = $this->model_catalog_vendor->getVendor($product['vendor_id']);

				foreach ($options as $option) {
					if ($option['type'] != 'file') {
						$option_data[] = array(
							'name'  => $option['name'],
							'value' => $option['value'],
							'type'  => $option['type']
						);
					} else {
						$upload_info = $this->model_tool_upload->getUploadByCode($option['value']);

						if ($upload_info) {
							$option_data[] = array(
								'name'  => $option['name'],
								'value' => $upload_info['name'],
								'type'  => $option['type'],
								'href'  => $this->url->link('tool/upload/download', 'token=' . $this->session->data['token'] . '&code=' . $upload_info['code'], 'SSL')
							);
						}
					}
				}

				$childproducts = NULL;

				if($product['product_type'] == 2){
					$childproducts = $this->model_sale_order->getchildorderproducts($product['order_product_id']);
				}

				foreach($childproducts as $key=>$val){
					// var_dump($val['lack_quantity']);
					// var_dump( $val['sumquan']);
					$childproducts[$key]['needed_quantity'] = $val['lack_quantity'] - $val['sumquan'] < 0?0:$val['lack_quantity'] - $val['sumquan'];
				}

				$data['products'][] = array(
					'order_product_id' => $product['order_product_id'],
					'childproducts'    => $childproducts,
					'product_id'       => $product['product_id'],
					'sku'    	 	   => $product['sku'],
					'name'    	 	   => $product['name'],
					'vname' 		   => $vname['vendor_name'],
					'model'    		   => $product['model'],
					'option'   		   => $option_data,
					'ship_status'	   => $product['ship_status'],
					'quantity'		   => $product['quantity'],
					'lack_quantity'    => $product['lack_quantity'],
					'sign_quantity'    => $product['sign_quantity'],
					'order_ids'	   => $product['order_ids'],
					'needed_quantity'  => $product['lack_quantity'] - $product['sumquan'] < 0?0:$product['lack_quantity'] - $product['sumquan'],
					'price'    		   => $this->currency->format($product['price'] + ($this->config->get('config_tax') ? $product['tax'] : 0), $order_info['currency_code'], $order_info['currency_value']),
					'total'    		   => $this->currency->format($product['total'] + ($this->config->get('config_tax') ? ($product['tax'] * $product['quantity']) : 0), $order_info['currency_code'], $order_info['currency_value']),
					'href'     		   => $this->url->link('catalog/product/edit', 'token=' . $this->session->data['token'] . '&product_id=' . $product['product_id'], 'SSL')
				);
				$total_ship_status *= $product['ship_status'];
			}

			$data['vouchers'] = array();

			$data['total_ship_status'] = $total_ship_status;
			$vouchers = $this->model_sale_order->getOrderVouchers($this->request->get['order_id']);

			foreach ($vouchers as $voucher) {
				$data['vouchers'][] = array(
					'description' => $voucher['description'],
					'amount'      => $this->currency->format($voucher['amount'], $order_info['currency_code'], $order_info['currency_value']),
					'href'        => $this->url->link('sale/voucher/edit', 'token=' . $this->session->data['token'] . '&voucher_id=' . $voucher['voucher_id'], 'SSL')
				);
			}

			$data['totals'] = array();

			$totals = $this->model_sale_order->getOrderTotals($this->request->get['order_id']);

			foreach ($totals as $total) {
				$data['totals'][] = array(
					'title' => $total['title'],
					'text'  => $this->currency->format($total['value'], $order_info['currency_code'], $order_info['currency_value']),
				);
			}

			$data['totals'][] = array(
				'title' => '原始价',
				'text' => $this->currency->format($order_info['ori_total'], $order_info['currency_code'], $order_info['currency_value']),
			);

			$data['comment'] = nl2br($order_info['comment']);

			$this->load->model('customer/customer');

			$data['reward'] = $order_info['reward'];

			switch ($order_info['bill_status']) {
				case '0':
					$data['is_invoice_text'] = $data['text_is_invoice_removed'];
					break;
				case '1':
					$data['is_invoice_text'] = $data['text_is_invoice_added'];
					break;
				case '2':
					$data['is_invoice_text'] = $data['text_is_invoice_passed'];
					break;
				default:
					# code...
					break;
			}
			$data['is_invoice'] = $order_info['bill_status'];

			$data['reward_total'] = $this->model_customer_customer->getTotalCustomerRewardsByOrderId($this->request->get['order_id']);

			$data['affiliate_fullname'] = $order_info['affiliate_fullname'];

			if ($order_info['affiliate_id']) {
				$data['affiliate'] = $this->url->link('marketing/affiliate/edit', 'token=' . $this->session->data['token'] . '&affiliate_id=' . $order_info['affiliate_id'], 'SSL');
			} else {
				$data['affiliate'] = '';
			}

			$data['commission'] = $this->currency->format($order_info['commission'], $order_info['currency_code'], $order_info['currency_value']);

			$this->load->model('marketing/affiliate');

			$data['commission_total'] = $this->model_marketing_affiliate->getTotalTransactionsByOrderId($this->request->get['order_id']);

			$this->load->model('localisation/order_status');

			$order_status_info = $this->model_localisation_order_status->getOrderStatus($order_info['order_status_id']);

			if ($order_status_info) {
				$data['order_status'] = $order_status_info['name'];
			} else {
				$data['order_status'] = '';
			}

			$data['order_statuses'] = $this->model_localisation_order_status->getOrderStatuses();

			$data['order_status_id'] = $order_info['order_status_id'];

			$data['account_custom_field'] = $order_info['custom_field'];

			$finance_group = $this->config->get('config_finance_user');
			$groupId = $this->user->getGroupId();
			$data['have_permission'] = false;
			$has_pay = $order_info['is_pay'];
			if(($groupId == $finance_group)&&(!$has_pay)){
				$data['have_permission'] = true;
			}

			// Custom Fields
			$this->load->model('customer/custom_field');

			$data['account_custom_fields'] = array();

			$filter_data = array(
				'sort'  => 'cf.sort_order',
				'order' => 'ASC',
			);

			$custom_fields = $this->model_customer_custom_field->getCustomFields($filter_data);

			foreach ($custom_fields as $custom_field) {
				if ($custom_field['location'] == 'account' && isset($order_info['custom_field'][$custom_field['custom_field_id']])) {
					if ($custom_field['type'] == 'select' || $custom_field['type'] == 'radio') {
						$custom_field_value_info = $this->model_customer_custom_field->getCustomFieldValue($order_info['custom_field'][$custom_field['custom_field_id']]);

						if ($custom_field_value_info) {
							$data['account_custom_fields'][] = array(
								'name'  => $custom_field['name'],
								'value' => $custom_field_value_info['name']
							);
						}
					}

					if ($custom_field['type'] == 'checkbox' && is_array($order_info['custom_field'][$custom_field['custom_field_id']])) {
						foreach ($order_info['custom_field'][$custom_field['custom_field_id']] as $custom_field_value_id) {
							$custom_field_value_info = $this->model_customer_custom_field->getCustomFieldValue($custom_field_value_id);

							if ($custom_field_value_info) {
								$data['account_custom_fields'][] = array(
									'name'  => $custom_field['name'],
									'value' => $custom_field_value_info['name']
								);
							}
						}
					}

					if ($custom_field['type'] == 'text' || $custom_field['type'] == 'textarea' || $custom_field['type'] == 'file' || $custom_field['type'] == 'date' || $custom_field['type'] == 'datetime' || $custom_field['type'] == 'time') {
						$data['account_custom_fields'][] = array(
							'name'  => $custom_field['name'],
							'value' => $order_info['custom_field'][$custom_field['custom_field_id']]
						);
					}

					if ($custom_field['type'] == 'file') {
						$upload_info = $this->model_tool_upload->getUploadByCode($order_info['custom_field'][$custom_field['custom_field_id']]);

						if ($upload_info) {
							$data['account_custom_fields'][] = array(
								'name'  => $custom_field['name'],
								'value' => $upload_info['name']
							);
						}
					}
				}
			}

			// Custom fields
			$data['payment_custom_fields'] = array();

			foreach ($custom_fields as $custom_field) {
				if ($custom_field['location'] == 'address' && isset($order_info['payment_custom_field'][$custom_field['custom_field_id']])) {
					if ($custom_field['type'] == 'select' || $custom_field['type'] == 'radio') {
						$custom_field_value_info = $this->model_customer_custom_field->getCustomFieldValue($order_info['payment_custom_field'][$custom_field['custom_field_id']]);

						if ($custom_field_value_info) {
							$data['payment_custom_fields'][] = array(
								'name'  => $custom_field['name'],
								'value' => $custom_field_value_info['name'],
								'sort_order' => $custom_field['sort_order']
							);
						}
					}

					if ($custom_field['type'] == 'checkbox' && is_array($order_info['payment_custom_field'][$custom_field['custom_field_id']])) {
						foreach ($order_info['payment_custom_field'][$custom_field['custom_field_id']] as $custom_field_value_id) {
							$custom_field_value_info = $this->model_customer_custom_field->getCustomFieldValue($custom_field_value_id);

							if ($custom_field_value_info) {
								$data['payment_custom_fields'][] = array(
									'name'  => $custom_field['name'],
									'value' => $custom_field_value_info['name'],
									'sort_order' => $custom_field['sort_order']
								);
							}
						}
					}

					if ($custom_field['type'] == 'text' || $custom_field['type'] == 'textarea' || $custom_field['type'] == 'file' || $custom_field['type'] == 'date' || $custom_field['type'] == 'datetime' || $custom_field['type'] == 'time') {
						$data['payment_custom_fields'][] = array(
							'name'  => $custom_field['name'],
							'value' => $order_info['payment_custom_field'][$custom_field['custom_field_id']],
							'sort_order' => $custom_field['sort_order']
						);
					}

					if ($custom_field['type'] == 'file') {
						$upload_info = $this->model_tool_upload->getUploadByCode($order_info['payment_custom_field'][$custom_field['custom_field_id']]);

						if ($upload_info) {
							$data['payment_custom_fields'][] = array(
								'name'  => $custom_field['name'],
								'value' => $upload_info['name'],
								'sort_order' => $custom_field['sort_order']
							);
						}
					}
				}
			}

			// Shipping
			$data['shipping_custom_fields'] = array();

			foreach ($custom_fields as $custom_field) {
				if ($custom_field['location'] == 'address' && isset($order_info['shipping_custom_field'][$custom_field['custom_field_id']])) {
					if ($custom_field['type'] == 'select' || $custom_field['type'] == 'radio') {
						$custom_field_value_info = $this->model_customer_custom_field->getCustomFieldValue($order_info['shipping_custom_field'][$custom_field['custom_field_id']]);

						if ($custom_field_value_info) {
							$data['shipping_custom_fields'][] = array(
								'name'  => $custom_field['name'],
								'value' => $custom_field_value_info['name'],
								'sort_order' => $custom_field['sort_order']
							);
						}
					}

					if ($custom_field['type'] == 'checkbox' && is_array($order_info['shipping_custom_field'][$custom_field['custom_field_id']])) {
						foreach ($order_info['shipping_custom_field'][$custom_field['custom_field_id']] as $custom_field_value_id) {
							$custom_field_value_info = $this->model_customer_custom_field->getCustomFieldValue($custom_field_value_id);

							if ($custom_field_value_info) {
								$data['shipping_custom_fields'][] = array(
									'name'  => $custom_field['name'],
									'value' => $custom_field_value_info['name'],
									'sort_order' => $custom_field['sort_order']
								);
							}
						}
					}

					if ($custom_field['type'] == 'text' || $custom_field['type'] == 'textarea' || $custom_field['type'] == 'file' || $custom_field['type'] == 'date' || $custom_field['type'] == 'datetime' || $custom_field['type'] == 'time') {
						$data['shipping_custom_fields'][] = array(
							'name'  => $custom_field['name'],
							'value' => $order_info['shipping_custom_field'][$custom_field['custom_field_id']],
							'sort_order' => $custom_field['sort_order']
						);
					}

					if ($custom_field['type'] == 'file') {
						$upload_info = $this->model_tool_upload->getUploadByCode($order_info['shipping_custom_field'][$custom_field['custom_field_id']]);

						if ($upload_info) {
							$data['shipping_custom_fields'][] = array(
								'name'  => $custom_field['name'],
								'value' => $upload_info['name'],
								'sort_order' => $custom_field['sort_order']
							);
						}
					}
				}
			}

			$data['ip'] = $order_info['ip'];
			$data['forwarded_ip'] = $order_info['forwarded_ip'];
			$data['user_agent'] = $order_info['user_agent'];
			$data['accept_language'] = $order_info['accept_language'];

			// Additional Tabs
			$data['tabs'] = array();

			$this->load->model('extension/extension');

			$content = $this->load->controller('payment/' . $order_info['payment_code'] . '/order');

			if ($content) {
				$this->load->language('payment/' . $order_info['payment_code']);

				$data['tabs'][] = array(
					'code'    => $order_info['payment_code'],
					'title'   => $this->language->get('heading_title'),
					'content' => $content
				);
			}

			$extensions = $this->model_extension_extension->getInstalled('fraud');

			foreach ($extensions as $extension) {
				if ($this->config->get($extension . '_status')) {
					$this->load->language('fraud/' . $extension);

					$content = $this->load->controller('fraud/' . $extension . '/order');

					if ($content) {
						$data['tabs'][] = array(
							'code'    => $extension,
							'title'   => $this->language->get('heading_title'),
							'content' => $content
						);
					}
				}
			}

			// API login
			$this->load->model('user/api');

			$api_info = $this->model_user_api->getApi($this->config->get('config_api_id'));

			if ($api_info) {
				$data['api_id'] = $api_info['api_id'];
				$data['api_key'] = $api_info['key'];
				$data['api_ip'] = $this->request->server['REMOTE_ADDR'];
			} else {
				$data['api_id'] = '';
				$data['api_key'] = '';
				$data['api_ip'] = '';
			}

			$data['tradeno_status'] = $this->model_sale_order->gettradeNo($order_id);
            $data['refundInfo'] = $this->model_sale_order->getOnlineRefundInfo($order_id, false);//在线退款信息
            $data['luckDrawAmount'] = $this->model_sale_order->getLuckDrawAmount($order_id, 7);//春节抽奖中奖信息，7是luckydraw表PK

			$data['header'] = $this->load->controller('common/header');
			$data['column_left'] = $this->load->controller('common/column_left');
			$data['footer'] = $this->load->controller('common/footer');

			$this->response->setOutput($this->load->view('sale/order_info.tpl', $data));
		} else {
			$this->load->language('error/not_found');

			$this->document->setTitle($this->language->get('heading_title'));

			$data['heading_title'] = $this->language->get('heading_title');

			$data['text_not_found'] = $this->language->get('text_not_found');

			$data['breadcrumbs'] = array();

			$data['breadcrumbs'][] = array(
				'text' => $this->language->get('text_home'),
				'href' => $this->url->link('common/dashboard', 'token=' . $this->session->data['token'], 'SSL')
			);

			$data['breadcrumbs'][] = array(
				'text' => $this->language->get('heading_title'),
				'href' => $this->url->link('error/not_found', 'token=' . $this->session->data['token'], 'SSL')
			);

			$data['header'] = $this->load->controller('common/header');
			$data['column_left'] = $this->load->controller('common/column_left');
			$data['footer'] = $this->load->controller('common/footer');

			$this->response->setOutput($this->load->view('error/not_found.tpl', $data));
		}
	}

	public function createInvoiceNo() {
		$this->load->language('sale/order');

		$json = array();

		if (!$this->user->hasPermission('modify', 'sale/order')) {
			$json['error'] = $this->language->get('error_permission');
		} elseif (isset($this->request->get['order_id'])) {
			if (isset($this->request->get['order_id'])) {
				$order_id = $this->request->get['order_id'];
			} else {
				$order_id = 0;
			}

			$this->load->model('sale/order');

			$invoice_no = $this->model_sale_order->createInvoiceNo($order_id);

			if ($invoice_no) {
				$json['invoice_no'] = $invoice_no;
			} else {
				$json['error'] = $this->language->get('error_action');
			}
		}

		$this->response->addHeader('Content-Type: application/json');
		$this->response->setOutput(json_encode($json));
	}

	public function addReward() {
		$this->load->language('sale/order');

		$json = array();

		if (!$this->user->hasPermission('modify', 'sale/order')) {
			$json['error'] = $this->language->get('error_permission');
		} else {
			if (isset($this->request->get['order_id'])) {
				$order_id = $this->request->get['order_id'];
			} else {
				$order_id = 0;
			}

			$this->load->model('sale/order');

			$order_info = $this->model_sale_order->getOrder($order_id);

			if ($order_info && $order_info['customer_id'] && ($order_info['reward'] > 0)) {
				$this->load->model('customer/customer');

				$reward_total = $this->model_customer_customer->getTotalCustomerRewardsByOrderId($order_id);

				if (!$reward_total) {
					$this->model_customer_customer->addReward($order_info['customer_id'], $this->language->get('text_order_id') . ' #' . $order_id, $order_info['reward'], $order_id);
				}
			}

			$json['success'] = $this->language->get('text_reward_added');
		}

		$this->response->addHeader('Content-Type: application/json');
		$this->response->setOutput(json_encode($json));
	}

	public function removeReward() {
		$this->load->language('sale/order');

		$json = array();

		if (!$this->user->hasPermission('modify', 'sale/order')) {
			$json['error'] = $this->language->get('error_permission');
		} else {
			if (isset($this->request->get['order_id'])) {
				$order_id = $this->request->get['order_id'];
			} else {
				$order_id = 0;
			}

			$this->load->model('sale/order');

			$order_info = $this->model_sale_order->getOrder($order_id);

			if ($order_info) {
				$this->load->model('customer/customer');

				$this->model_customer_customer->deleteReward($order_id);
			}

			$json['success'] = $this->language->get('text_reward_removed');
		}

		$this->response->addHeader('Content-Type: application/json');
		$this->response->setOutput(json_encode($json));
	}

		public function saveIs_invoice() {
		$this->load->language('sale/order');

		$json = array();
		if ( $_SERVER['REQUEST_METHOD'] === 'POST' ){

		if (!$this->user->hasPermission('modify', 'sale/order')) {
			$json['error'] = $this->language->get('error_permission');
		} else {
			if (isset($this->request->get['order_id'])) {
				$order_id = $this->request->get['order_id'];

			} else {
				$order_id = 0;
			}

			$json['success'] = '';
			if($order_id){
				$this->load->model('sale/order');

				$order_info = $this->model_sale_order->getOrder($order_id);

				if ($order_info && $order_info['customer_id'] && isset($this->request->post['is_invoice_id'])) {

					switch ($this->request->post['is_invoice_id']) {
						case '0':

							$this->model_sale_order->saveIs_invoice($order_id,'0');
							$json['success'] = $this->language->get('text_is_invoice_removed');
							$json['is_invoice_id'] = '0';
							break;
						case '1':
							$this->model_sale_order->saveIs_invoice($order_id,'1');
							$json['success'] = $this->language->get('text_is_invoice_added');
							$json['is_invoice_id'] = '1';
							break;
						case '2':
							$this->model_sale_order->saveIs_invoice($order_id,'2');
							$json['success'] = $this->language->get('text_is_invoice_passed');
							$json['is_invoice_id'] = '2';
							break;
						default:
							break;
					}
				}
			}
			$json['order_id']=$order_id;
		}

		$this->response->addHeader('Content-Type: application/json');
		$this->response->setOutput(json_encode($json));
		}
	}

	public function removeIs_invoice() {
		$this->load->language('sale/order');

		$json = array();

		if (!$this->user->hasPermission('modify', 'sale/order')) {
			$json['error'] = $this->language->get('error_permission');
		} else {
			if (isset($this->request->get['order_id'])) {
				$order_id = $this->request->get['order_id'];
			} else {
				$order_id = 0;
			}

			$this->load->model('sale/order');

			$order_info = $this->model_sale_order->getOrder($order_id);

			if ($order_info) {

				$this->model_sale_order->deleteIs_invoice($order_id);
			}

			$json['success'] = $this->language->get('text_is_invoice_removed');
		}

		$this->response->addHeader('Content-Type: application/json');
		$this->response->setOutput(json_encode($json));
	}

	public function addCommission() {
		$this->load->language('sale/order');

		$json = array();

		if (!$this->user->hasPermission('modify', 'sale/order')) {
			$json['error'] = $this->language->get('error_permission');
		} else {
			if (isset($this->request->get['order_id'])) {
				$order_id = $this->request->get['order_id'];
			} else {
				$order_id = 0;
			}

			$this->load->model('sale/order');

			$order_info = $this->model_sale_order->getOrder($order_id);

			if ($order_info) {
				$this->load->model('marketing/affiliate');

				$affiliate_total = $this->model_marketing_affiliate->getTotalTransactionsByOrderId($order_id);

				if (!$affiliate_total) {
					$this->model_marketing_affiliate->addTransaction($order_info['affiliate_id'], $this->language->get('text_order_id') . ' #' . $order_id, $order_info['commission'], $order_id);
				}
			}

			$json['success'] = $this->language->get('text_commission_added');
		}

		$this->response->addHeader('Content-Type: application/json');
		$this->response->setOutput(json_encode($json));
	}

	public function removeCommission() {
		$this->load->language('sale/order');

		$json = array();

		if (!$this->user->hasPermission('modify', 'sale/order')) {
			$json['error'] = $this->language->get('error_permission');
		} else {
			if (isset($this->request->get['order_id'])) {
				$order_id = $this->request->get['order_id'];
			} else {
				$order_id = 0;
			}

			$this->load->model('sale/order');

			$order_info = $this->model_sale_order->getOrder($order_id);

			if ($order_info) {
				$this->load->model('marketing/affiliate');

				$this->model_marketing_affiliate->deleteTransaction($order_id);
			}

			$json['success'] = $this->language->get('text_commission_removed');
		}

		$this->response->addHeader('Content-Type: application/json');
		$this->response->setOutput(json_encode($json));
	}

	public function history() {
		$this->load->language('sale/order');

		$data['text_no_results'] = $this->language->get('text_no_results');

		$data['column_date_added'] = $this->language->get('column_date_added');
		$data['column_status'] = $this->language->get('column_status');
		$data['column_notify'] = $this->language->get('column_notify');
		$data['column_comment'] = $this->language->get('column_comment');

		if (isset($this->request->get['page'])) {
			$page = $this->request->get['page'];
		} else {
			$page = 1;
		}

		$data['histories'] = array();

		$this->load->model('sale/order');

		$results = $this->model_sale_order->getOrderHistories($this->request->get['order_id'], ($page - 1) * 10, 10);

		// $this->load->model('catalog/vendor');

		foreach ($results as $result) {
			// $vendor_info = $this->model_catalog_vendor->getVendor($result['vendor_id']);
			// if (!empty($vendor_info)) {
			// 	$vendor_name = $vendor_info['vendor_name'];
			// } else {
			// 	$vendor_name = $this->language->get('text_default_store');
			// }

			$data['histories'][] = array(
				'notify'     => $result['notify'] ? $this->language->get('text_yes') : $this->language->get('text_no'),
				'status'     => $result['status'],
				'comment'    => nl2br($result['comment']),
				'date_added' => date($this->language->get('date_format_short'), strtotime($result['date_added']))
			);
		}

		$history_total = $this->model_sale_order->getTotalOrderHistories($this->request->get['order_id']);

		$pagination = new Pagination();
		$pagination->total = $history_total;
		$pagination->page = $page;
		$pagination->limit = 10;
		$pagination->url = $this->url->link('sale/order/history', 'token=' . $this->session->data['token'] . '&order_id=' . $this->request->get['order_id'] . '&page={page}', 'SSL');

		$data['pagination'] = $pagination->render();

		$data['results'] = sprintf($this->language->get('text_pagination'), ($history_total) ? (($page - 1) * 10) + 1 : 0, ((($page - 1) * 10) > ($history_total - 10)) ? $history_total : ((($page - 1) * 10) + 10), $history_total, ceil($history_total / 10));

		$this->response->setOutput($this->load->view('sale/order_history.tpl', $data));
	}

	public function invoice() {
		$this->load->language('sale/order');

		$data['title'] = $this->language->get('text_invoice');

		if ($this->request->server['HTTPS']) {
			$data['base'] = HTTPS_SERVER;
		} else {
			$data['base'] = HTTP_SERVER;
		}

		$data['direction'] = $this->language->get('direction');
		$data['lang'] = $this->language->get('code');

		$data['text_invoice'] = $this->language->get('text_invoice');
		$data['text_order_detail'] = $this->language->get('text_order_detail');
		$data['text_order_id'] = $this->language->get('text_order_id');
		$data['text_invoice_no'] = $this->language->get('text_invoice_no');
		$data['text_invoice_date'] = $this->language->get('text_invoice_date');
		$data['text_date_added'] = $this->language->get('text_date_added');
		$data['text_telephone'] = $this->language->get('text_telephone');
		$data['text_fax'] = $this->language->get('text_fax');
		$data['text_email'] = $this->language->get('text_email');
		$data['text_website'] = $this->language->get('text_website');
		$data['text_payment_address'] = $this->language->get('text_payment_address');
		$data['text_shipping_address'] = $this->language->get('text_shipping_address');
		$data['text_payment_method'] = $this->language->get('text_payment_method');
		$data['text_shipping_method'] = $this->language->get('text_shipping_method');
		$data['text_comment'] = $this->language->get('text_comment');

		$data['column_product'] = $this->language->get('column_product');
		$data['column_model'] = $this->language->get('column_model');
		$data['column_quantity'] = $this->language->get('column_quantity');
		$data['column_price'] = $this->language->get('column_price');
		$data['column_total'] = $this->language->get('column_total');

		$this->load->model('sale/order');

		$this->load->model('setting/setting');

		$data['orders'] = array();

		$orders = array();

		if (isset($this->request->post['selected'])) {
			$orders = $this->request->post['selected'];
		} elseif (isset($this->request->get['order_id'])) {
			$orders[] = $this->request->get['order_id'];
		}

		foreach ($orders as $order_id) {
			$order_info = $this->model_sale_order->getOrder($order_id);

			if ($order_info) {
				$store_info = $this->model_setting_setting->getSetting('config', $order_info['store_id']);

				if ($store_info) {
					$store_address = $store_info['config_address'];
					$store_email = $store_info['config_email'];
					$store_telephone = $store_info['config_telephone'];
					$store_fax = $store_info['config_fax'];
				} else {
					$store_address = $this->config->get('config_address');
					$store_email = $this->config->get('config_email');
					$store_telephone = $this->config->get('config_telephone');
					$store_fax = $this->config->get('config_fax');
				}

				if ($order_info['invoice_no']) {
					$invoice_no = $order_info['invoice_prefix'] . $order_info['invoice_no'];
				} else {
					$invoice_no = '';
				}

				if ($order_info['payment_address_format']) {
					$format = $order_info['payment_address_format'];
				} else {
					$format = '{fullname}' . "\n" . '{company}' . "\n" . '{address}' . "\n" . '{city} {postcode}' . "\n" . '{zone}' . "\n" . '{country}';
				}

				$find = array(
					'{fullname}',
					'{company}',
					'{address}',
					'{city}',
					'{postcode}',
					'{zone}',
					'{zone_code}',
					'{country}'

				);

				$replace = array(
					'fullname' => $order_info['payment_fullname'],
					'company'   => $order_info['payment_company'],
					'address' => $order_info['payment_address'],
					'city'      => $order_info['payment_city'],
					'postcode'  => $order_info['payment_postcode'],
					'zone'      => $order_info['payment_zone'],
					'zone_code' => $order_info['payment_zone_code'],
					'country'   => $order_info['payment_country']

				);

				$payment_address = str_replace(array("\r\n", "\r", "\n"), '<br />', preg_replace(array("/\s\s+/", "/\r\r+/", "/\n\n+/"), '<br />', trim(str_replace($find, $replace, $format))));

				if ($order_info['shipping_address_format']) {
					$format = $order_info['shipping_address_format'];
				} else {
					$format = '{fullname}' . "\n" . '{company}' . "\n" . '{address}' . "\n" . '{city} {postcode}' . "\n" . '{zone}' . "\n" . '{country}' . "\n" . '{shipping_telephone}';
				}

				$find = array(
					'{fullname}',
					'{company}',
					'{address}',
					'{city}',
					'{postcode}',
					'{zone}',
					'{zone_code}',
					'{country}',
					'{shipping_telephone}'
				);

				$replace = array(
					'fullname' => $order_info['shipping_fullname'],
					'company'   => $order_info['shipping_company'],
					'address' => $order_info['shipping_address'],
					'city'      => $order_info['shipping_city'],
					'postcode'  => $order_info['shipping_postcode'],
					'zone'      => $order_info['shipping_zone'],
					'zone_code' => $order_info['shipping_zone_code'],
					'country'   => $order_info['shipping_country'],
					'shipping_address'   => $order_info['shipping_telephone']
				);

				$shipping_address = str_replace(array("\r\n", "\r", "\n"), '<br />', preg_replace(array("/\s\s+/", "/\r\r+/", "/\n\n+/"), '<br />', trim(str_replace($find, $replace, $format))));

				$this->load->model('tool/upload');

				$product_data = array();

				$products = $this->model_sale_order->getOrderProducts($order_id);

				foreach ($products as $product) {
					$option_data = array();

					$options = $this->model_sale_order->getOrderOptions($order_id, $product['order_product_id']);

					foreach ($options as $option) {
						if ($option['type'] != 'file') {
							$value = $option['value'];
						} else {
							$upload_info = $this->model_tool_upload->getUploadByCode($option['value']);

							if ($upload_info) {
								$value = $upload_info['name'];
							} else {
								$value = '';
							}
						}

						$option_data[] = array(
							'name'  => $option['name'],
							'value' => $value
						);
					}

					$product_data[] = array(
						'name'     => $product['name'],
						'model'    => $product['model'],
						'option'   => $option_data,
						'quantity' => $product['quantity'],
						'price'    => $this->currency->format($product['price'] + ($this->config->get('config_tax') ? $product['tax'] : 0), $order_info['currency_code'], $order_info['currency_value']),
						'total'    => $this->currency->format($product['total'] + ($this->config->get('config_tax') ? ($product['tax'] * $product['quantity']) : 0), $order_info['currency_code'], $order_info['currency_value'])
					);
				}

				$voucher_data = array();

				$vouchers = $this->model_sale_order->getOrderVouchers($order_id);

				foreach ($vouchers as $voucher) {
					$voucher_data[] = array(
						'description' => $voucher['description'],
						'amount'      => $this->currency->format($voucher['amount'], $order_info['currency_code'], $order_info['currency_value'])
					);
				}

				$total_data = array();

				$totals = $this->model_sale_order->getOrderTotals($order_id);

				foreach ($totals as $total) {
					$total_data[] = array(
						'title' => $total['title'],
						'text'  => $this->currency->format($total['value'], $order_info['currency_code'], $order_info['currency_value']),
					);
				}

				$data['orders'][] = array(
					'order_id'	         => $order_id,
					'invoice_no'         => $invoice_no,
					'date_added'         => date($this->language->get('date_format_short'), strtotime($order_info['date_added'])),
					'store_name'         => $order_info['store_name'],
					'store_url'          => rtrim($order_info['store_url'], '/'),
					'store_address'      => nl2br($store_address),
					'store_email'        => $store_email,
					'store_telephone'    => $store_telephone,
					'store_fax'          => $store_fax,
					'email'              => $order_info['email'],
					'telephone'          => $order_info['telephone'],
					'shipping_address'   => $shipping_address,
					'shipping_method'    => $order_info['shipping_method'],
					'payment_address'    => $payment_address,
					'payment_method'     => $order_info['payment_method'],
					'product'            => $product_data,
					'voucher'            => $voucher_data,
					'total'              => $total_data,
					'comment'            => nl2br($order_info['comment'])
				);
			}
		}

		$this->response->setOutput($this->load->view('sale/order_invoice.tpl', $data));
	}

	public function shipping() {
		$this->load->language('sale/order');

		$data['title'] = $this->language->get('text_shipping');

		if ($this->request->server['HTTPS']) {
			$data['base'] = HTTPS_SERVER;
		} else {
			$data['base'] = HTTP_SERVER;
		}

		$data['direction'] = $this->language->get('direction');
		$data['lang'] = $this->language->get('code');

		$data['text_shipping'] = $this->language->get('text_shipping');
		$data['text_picklist'] = $this->language->get('text_picklist');
		$data['text_order_detail'] = $this->language->get('text_order_detail');
		$data['text_order_id'] = $this->language->get('text_order_id');
		$data['text_invoice_no'] = $this->language->get('text_invoice_no');
		$data['text_invoice_date'] = $this->language->get('text_invoice_date');
		$data['text_date_added'] = $this->language->get('text_date_added');
		$data['text_telephone'] = $this->language->get('text_telephone');
		$data['text_fax'] = $this->language->get('text_fax');
		$data['text_email'] = $this->language->get('text_email');
		$data['text_website'] = $this->language->get('text_website');
		$data['text_contact'] = $this->language->get('text_contact');
		$data['text_payment_address'] = $this->language->get('text_payment_address');
		$data['text_shipping_method'] = $this->language->get('text_shipping_method');
		$data['text_sku'] = $this->language->get('text_sku');
		$data['text_upc'] = $this->language->get('text_upc');
		$data['text_ean'] = $this->language->get('text_ean');
		$data['text_jan'] = $this->language->get('text_jan');
		$data['text_isbn'] = $this->language->get('text_isbn');
		$data['text_mpn'] = $this->language->get('text_mpn');
		$data['text_shipping_telephone'] = $this->language->get('text_shipping_telephone');
		$data['text_comment'] = $this->language->get('text_comment');

		$data['column_location'] = $this->language->get('column_location');
		$data['column_reference'] = $this->language->get('column_reference');
		$data['column_product'] = $this->language->get('column_product');
		$data['column_weight'] = $this->language->get('column_weight');
		$data['column_model'] = $this->language->get('column_model');
		$data['column_quantity'] = $this->language->get('column_quantity');

		$this->load->model('sale/order');

		$this->load->model('catalog/product');

		$this->load->model('setting/setting');

		$data['orders'] = array();

		$orders = array();

		if (isset($this->request->post['selected'])) {
			$orders = $this->request->post['selected'];
		} elseif (isset($this->request->get['order_id'])) {
			$orders[] = $this->request->get['order_id'];
		}

		foreach ($orders as $order_id) {
			$order_info = $this->model_sale_order->getOrder($order_id);

			// Make sure there is a shipping method
			if ($order_info && $order_info['shipping_code']) {
				$store_info = $this->model_setting_setting->getSetting('config', $order_info['store_id']);

				if ($store_info) {
					$store_address = $store_info['config_address'];
					$store_email = $store_info['config_email'];
					$store_telephone = $store_info['config_telephone'];
					$store_fax = $store_info['config_fax'];
				} else {
					$store_address = $this->config->get('config_address');
					$store_email = $this->config->get('config_email');
					$store_telephone = $this->config->get('config_telephone');
					$store_fax = $this->config->get('config_fax');
				}

				if ($order_info['invoice_no']) {
					$invoice_no = $order_info['invoice_prefix'] . $order_info['invoice_no'];
				} else {
					$invoice_no = '';
				}

				if ($order_info['shipping_address_format']) {
					$format = $order_info['shipping_address_format'];
				} else {
					$format = '{fullname}' . "\n" . '{company}' . "\n" . '{address}' . "\n" . '{city} {postcode}' . "\n" . '{zone}' . "\n" . '{country}';
				}

				$find = array(
					'{fullname}',
					'{company}',
					'{address}',
					'{city}',
					'{postcode}',
					'{zone}',
					'{zone_code}',
					'{country}'
				);

				$replace = array(
					'fullname' => $order_info['shipping_fullname'],
					'company'   => $order_info['shipping_company'],
					'address' => $order_info['shipping_address'],
					'city'      => $order_info['shipping_city'],
					'postcode'  => $order_info['shipping_postcode'],
					'zone'      => $order_info['shipping_zone'],
					'zone_code' => $order_info['shipping_zone_code'],
					'country'   => $order_info['shipping_country']
				);

				$shipping_address = str_replace(array("\r\n", "\r", "\n"), '<br />', preg_replace(array("/\s\s+/", "/\r\r+/", "/\n\n+/"), '<br />', trim(str_replace($find, $replace, $format))));

				$this->load->model('tool/upload');

				$product_data = array();

				$products = $this->model_sale_order->getOrderProducts($order_id);

				foreach ($products as $product) {
					$option_weight = '';

					$product_info = $this->model_catalog_product->getProduct($product['product_id']);

					if ($product_info) {
						$option_data = array();

						$options = $this->model_sale_order->getOrderOptions($order_id, $product['order_product_id']);

						foreach ($options as $option) {
							$option_value_info = $this->model_catalog_product->getProductOptionValue($order_id, $product['order_product_id']);

							if ($option['type'] != 'file') {
								$value = $option['value'];
							} else {
								$upload_info = $this->model_tool_upload->getUploadByCode($option['value']);

								if ($upload_info) {
									$value = $upload_info['name'];
								} else {
									$value = '';
								}
							}

							$option_data[] = array(
								'name'  => $option['name'],
								'value' => $value
							);

							$product_option_value_info = $this->model_catalog_product->getProductOptionValue($product['product_id'], $option['product_option_value_id']);

							if ($product_option_value_info) {
								if ($product_option_value_info['weight_prefix'] == '+') {
									$option_weight += $product_option_value_info['weight'];
								} elseif ($product_option_value_info['weight_prefix'] == '-') {
									$option_weight -= $product_option_value_info['weight'];
								}
							}
						}

						$product_data[] = array(
							'name'     => $product_info['name'],
							'model'    => $product_info['model'],
							'option'   => $option_data,
							'quantity' => $product['quantity'],
							'location' => $product_info['location'],
							'sku'      => $product_info['sku'],
							'upc'      => $product_info['upc'],
							'ean'      => $product_info['ean'],
							'jan'      => $product_info['jan'],
							'isbn'     => $product_info['isbn'],
							'mpn'      => $product_info['mpn'],
							'weight'   => $this->weight->format(($product_info['weight'] + $option_weight) * $product['quantity'], $product_info['weight_class_id'], $this->language->get('decimal_point'), $this->language->get('thousand_point'))
						);
					}
				}








				$data['orders'][] = array(
					'order_id'	       => $order_id,
					'invoice_no'       => $invoice_no,
					'date_added'       => date($this->language->get('date_format_short'), strtotime($order_info['date_added'])),
					'store_name'       => $order_info['store_name'],
					'store_url'        => rtrim($order_info['store_url'], '/'),
					'store_address'    => nl2br($store_address),
					'store_email'      => $store_email,
					'store_telephone'  => $store_telephone,
					'store_fax'        => $store_fax,
					'email'            => $order_info['email'],
					'telephone'        => $order_info['telephone'],
					'shipping_telephone' => $order_info['shipping_telephone'],
					'shipping_address' => $shipping_address,
					'shipping_method'  => $order_info['shipping_method'],
					'product'          => $product_data,
					'comment'          => nl2br($order_info['comment'])
				);
			}
		}

		$this->response->setOutput($this->load->view('sale/order_shipping.tpl', $data));
	}

	public function export(){
    $order_id = I('get.order_id');
    if(!$order_id){
      $order_id = 0;
    }
    $this->load->model('sale/order');
    $sc = $this->model_sale_order->getSc($order_id);

    $data['sc'] = $sc;
    if(!$sc){
      $this->load->language('error/not_found');
 
      $this->document->setTitle($this->language->get('heading_title'));

      $data['heading_title'] = $this->language->get('heading_title');
 
      $data['text_not_found'] = $this->language->get('text_not_found');
 
      $data['breadcrumbs'] = array();

      $data['breadcrumbs'][] = array(
        'text' => $this->language->get('heading_title'),
        'href' => $this->url->link('error/not_found', 'token=' . $this->session->data['token'], 'SSL')
      );
 

      $data['footer'] = $this->load->controller('common/footer');
 
      $this->response->setOutput($this->load->view('error/not_found.tpl', $data));
    }
    $this->load->library('PHPExcel/PHPExcel');
    $objReader = PHPExcel_IOFactory::createReader('Excel5');
    $objPHPExcel = $objReader->load(DIR_SYSTEM . "template/order_tpl.xls"); 
    $objPHPExcel->getProperties()->setCreator("Think-tec")
               ->setLastModifiedBy("Think-tec")
               ->setTitle("Bai Huo Zhan SC")
               ->setSubject("Bai Huo Zhan SC")
               ->setDescription("Bai Huo Zhan SC")
               ->setKeywords("Bai Huo Zhan, Think-tec")
               ->setCategory("Think-tec");
    // $objPHPExcel->setActiveSheetIndex(0);
    $objActSheet = $objPHPExcel->getActiveSheet();
    $objActSheet->setCellValue('B2', $sc['company_name']);  
    $objPHPExcel->getActiveSheet()->getStyle('B2')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
    $objActSheet->setCellValue('C2', $sc['shipping_address']);  
    $objPHPExcel->getActiveSheet()->getStyle('C2')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
    // $objPHPExcel->getActiveSheet()->getStyle('C2')->getAlignment()->setWrapText(true); 
    $objActSheet->setCellValue('B3', $sc['order_id']);  
    $objPHPExcel->getActiveSheet()->getStyle('B3')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
    
    $date_added = substr($sc['date_added'], 0, 10);
    $objActSheet->setCellValue('B4', $date_added);
    $objActSheet->setCellValue('F3', $sc['customer_id']);
    $objActSheet->setCellValue('F4', $sc['fullname']);
    $objActSheet->setCellValue('F5', $sc['shipping_fullname']);
    $objActSheet->setCellValue('F6', $sc['telephone']);
    $objActSheet->setCellValue('D4', $sc['payment_method']);
    $objActSheet->setCellValue('D5', (int)$sc['is_pay']?'已支付':'未支付');

    $row_num = 9;
    $styleBorderOutline = array(
      'borders' => array(
        'outline' => array(
          'style' => PHPExcel_Style_Border::BORDER_THIN,
        ),
      ),
    );
    $objPHPExcel->getActiveSheet()->insertNewRowBefore(9, count($sc['products']));
    $count = 0;
    foreach ($sc['products'] as $key => $sc_product) {
      
      $objActSheet->setCellValue('A'.$row_num, $sc_product['order_ids']);
      // $objActSheet->setCellValue('B'.$row_num, $sc['order_id']);
      $objActSheet->setCellValue('B'.$row_num, $sc_product['product_name']);
      $objActSheet->setCellValue('C'.$row_num, $sc_product['sku']);
      $objActSheet->setCellValue('D'.$row_num, $sc_product['quantity']);
      $objActSheet->setCellValue('E'.$row_num, $sc_product['price']);
      $objActSheet->setCellValue('F'.$row_num, $sc_product['total']);

      // $count += $sc_product['qty'];

      $objPHPExcel->getActiveSheet()->getStyle('A'.$row_num)->applyFromArray($styleBorderOutline);
      $objPHPExcel->getActiveSheet()->getStyle('B'.$row_num)->applyFromArray($styleBorderOutline);
      $objPHPExcel->getActiveSheet()->getStyle('C'.$row_num)->applyFromArray($styleBorderOutline);
      $objPHPExcel->getActiveSheet()->getStyle('D'.$row_num)->applyFromArray($styleBorderOutline);
      $objPHPExcel->getActiveSheet()->getStyle('E'.$row_num)->applyFromArray($styleBorderOutline);
      $objPHPExcel->getActiveSheet()->getStyle('F'.$row_num)->applyFromArray($styleBorderOutline);
      // $objPHPExcel->getActiveSheet()->getStyle('G'.$row_num)->applyFromArray($styleBorderOutline);
      $row_num++;
    }

    $info =  M("order_total")->where(array('order_id'=>$order_id))->select();
	
	$row_num = $row_num+1;
    $objPHPExcel->getActiveSheet()->insertNewRowBefore($row_num, count($info));

    // var_dump($info);
    foreach ($info as $key => $value) {
      // var_dump($row_num);
      // var_dump($value);die();
      // var_dump($value['value']);
      // $objActSheet->setCellValue('A'.$row_num, '1');
      // $objActSheet->setCellValue('B'.$row_num, '1');
      // $objActSheet->setCellValue('C'.$row_num, '1');
      $objActSheet->setCellValue('D'.$row_num, $value['title'].': ');
      $objActSheet->setCellValue('F'.$row_num, "¥".$value['value']);
      // $objActSheet->setCellValue('E'.$row_num, '1');
      // $objActSheet->setCellValue('F'.$row_num, '1');

      $row_num++;

    }

    $objActSheet->setCellValue('A'.$row_num, "总累计积分：".$sc['Areward']);
    $objActSheet->setCellValue('B'.$row_num, "本月积分：".$sc['Mreward']);
    $objActSheet->setCellValue('D'.$row_num, $sc['Mtotal_order']);
    $objActSheet->setCellValue('F'.$row_num, "¥".$sc['Mtotal_money']);
    $row_num++;

    $objActSheet->setCellValue('A'.$row_num, '数量合计数: ' . $sc['total_item_number']);
    $objActSheet->setCellValue('D'.$row_num, '金额总计: ' . $sc['total']);

    $objPHPExcel->getActiveSheet()->getStyle('A7:G'.$row_num)->getFont()->setSize(9);
    $objPHPExcel->getActiveSheet()->getStyle('A1:G'.$row_num)->getAlignment()->setWrapText(true); 
    $row_num++;



    $objActSheet->setTitle('百货栈商超对账单');


    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
    ob_end_clean();
    // Redirect output to a client’s web browser (Excel2007)
    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    header('Content-Disposition: attachment;filename="SC_BHZ_'.date('Y-m-d-H-i',time()).'.xlsx"');
    header('Cache-Control: max-age=0');
    // If you're serving to IE 9, then the following may be needed
    header('Cache-Control: max-age=1');
    // If you're serving to IE over SSL, then the following may be needed
    header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
    header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
    header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
    header ('Pragma: public'); // HTTP/1.0
    $objWriter->save('php://output'); 
    exit;
  }
  function validateDate($date, $format = 'Y-m-d H:i:s')
	{
	    $d = DateTime::createFromFormat($format, $date);
	    return $d && $d->format($format) == $date;
	}

  public function genLogcenterBill(){
  	$logcenter_bill_month = I('get.year_month');
  	$month_valid = $this->validateDate($logcenter_bill_month, 'Y-m');
  	if(!$month_valid) {
  		$this->session->data['error'] = '请选择有效的年月日期';
  		$this->response->redirect($this->url->link('sale/order', 'token=' . $this->session->data['token'], 'SSL'));
  	}
  	//获取选择月份之前半年内所有还未对账的完成状态的订单
  	$d = DateTime::createFromFormat('Y-m', $logcenter_bill_month);
  	$cur_year_month = $d->format('Y-m-01');
  	// $cur_month = $d->format('Y-m-21');
  	$d->modify('+1 month');
  	$cur_month = $d->format('Y-m-01');
  	$d->modify('-7 month');
  	$end_month = $d->format('Y-m-d');
  	$this->load->model('sale/logcenter_bill');
  	$this->load->model('sale/order');
  	$this->load->model('catalog/logcenter');
  	$billed_orders = $this->model_sale_logcenter_bill->getBilledOrders($cur_month, $end_month);
  	$billed_order_ids = array();
  	foreach ($billed_orders as $bo) {
  		$billed_order_ids[] = $bo['order_id'];
  	}

  	// $billed_order_ids = implode(',', $billed_order_ids);
  	$logcenter_ids = $this->model_sale_order->getLogcenterIdsFromOrders($cur_month, $end_month, $billed_order_ids);

  	foreach ($logcenter_ids as $logcenter_id) {
      $bill_data = $this->model_sale_order->getToBillOrders($cur_month, $end_month, $billed_order_ids, $logcenter_id['logcenter_id']);
      $bill_data_full[$logcenter_id['logcenter_id']] = $bill_data;
    }

    foreach ($bill_data_full as $logcenter_id=>$bill_data) {
    	$logcenters_info = $this->model_catalog_logcenter->getLogcenter($logcenter_id);
    	$commission = (float)$logcenters_info['commission']/100; //物流营销中心抽取的订单总数的百分比
    	$order_total = 0;
    	$order_ids = array();
    	foreach ($bill_data as $order) {
    		$order_total += (float)$order['total'];
    		$order_ids[] = $order['order_id'];
    	}
    	$commission_total = $order_total*$commission;
    	$data = array();
    	$data['logcenter_id'] = $logcenter_id;
    	$data['year_month'] = $cur_year_month;
    	$data['total'] = $commission_total;
    	$data['order_total'] = $order_total;
    	$data['commission'] = $commission*100;
    	$data['date_added'] = date('Y-m-d H:i:s', time());
    	$logcenter_bill_id = $this->model_sale_logcenter_bill->saveLogcenterBill($data, $order_ids);

    	//添加生成po操作记录
      $this->load->model('user/user');
      $user_info = $this->model_user_user->getUser($this->user->getId());
      $comment = '新增物流营销对账单';
      $this->model_sale_logcenter_bill->addLogcenterBillHistory($logcenter_bill_id, $this->user->getId(), $user_info['fullname'], $comment);
    }

    $this->session->data['success'] = '生成物流营销中心对账单成功';
  	$this->response->redirect($this->url->link('sale/logcenter_bill', 'token=' . $this->session->data['token'], 'SSL'));
  }

  public function monthlyExport() {
		$logcenter_bill_month = I('get.year_month');
  	$month_valid = $this->validateDate($logcenter_bill_month, 'Y-m');
  	if(!$month_valid) {
  		$this->session->data['error'] = '请选择有效的年月日期';
  		$this->response->redirect($this->url->link('sale/order', 'token=' . $this->session->data['token'], 'SSL'));
  	}
  	//获取选择月份之前半年内所有还未对账的完成状态的订单
  	$d = DateTime::createFromFormat('Y-m', $logcenter_bill_month);
  	$cur_year_month = $d->format('Y-m-01');
  	$cur_month = $d->format('Y-m-21');
  	$d->modify('-6 month');
  	$end_month = $d->format('Y-m-d');
  	$this->load->model('sale/logcenter_bill');
  	$this->load->model('sale/order');
  	$this->load->model('catalog/logcenter');
  	$billed_orders = $this->model_sale_logcenter_bill->getBilledOrders($cur_month, $end_month);
  	$billed_order_ids = array();
  	foreach ($billed_orders as $bo) {
  		$billed_order_ids[] = $bo['order_id'];
  	}
  	$results = $this->model_sale_order->getToBillOrdersForExport($cur_month, $end_month, $billed_order_ids);

		$this->load->library('PHPExcel/PHPExcel');
		$objPHPExcel = new PHPExcel();
		$objProps = $objPHPExcel->getProperties();
		$objProps->setCreator("Think-tec");
		$objProps->setLastModifiedBy("Think-tec");
		$objProps->setTitle("Think-tec Contact");
		$objProps->setSubject("Think-tec Contact Data");
		$objProps->setDescription("Think-tec Contact Data");
		$objProps->setKeywords("Think-tec Contact");
		$objProps->setCategory("Think-tec");
		$objPHPExcel->setActiveSheetIndex(0);
		$objActSheet = $objPHPExcel->getActiveSheet();

		$objActSheet->setTitle('Sheet1');
		$col_idx = 'A';
		$headers = array('订单号','订单状态','收货人公司','收货人','电话','省市','市县','县区','地址','订单总额','物流中心','下单时间');
		$row_keys = array('order_id','status','shipping_company','shipping_fullname','shipping_telephone','shipping_country','shipping_zone','shipping_city','shipping_address','total','logcenter_name','date_added');
		foreach ($headers as $header) {
			$objActSheet->setCellValue($col_idx++.'1', $header);
		}
		//添加物流信息
		$i = 2;
		foreach ($results as $rlst) {
			$col_idx = 'A';
			foreach ($row_keys as $rk) {
				// $objActSheet->setCellValue($col_idx++.$i, $rlst[$rk]);
				$objActSheet->setCellValueExplicit($col_idx++.$i, $rlst[$rk], PHPExcel_Cell_DataType::TYPE_STRING);
			}
			$i++;
		}

		$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');

		ob_end_clean();
		// Redirect output to a client’s web browser (Excel2007)
		header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
		header('Content-Disposition: attachment;filename="Orders_'.date('Y-m-d',time()).'.xlsx"');
		header('Cache-Control: max-age=0');
		// If you're serving to IE 9, then the following may be needed
		header('Cache-Control: max-age=1');

		// If you're serving to IE over SSL, then the following may be needed
		header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
		header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
		header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
		header ('Pragma: public'); // HTTP/1.0
    $objWriter->save('php://output');
    exit;
	}

    //导出指定单品订单
    public function exportSpecial() {
        if (isset($this->request->get['filter_order_id'])) {
            $filter_order_id = $this->request->get['filter_order_id'];
        } else {
            $filter_order_id = null;
        }
        if (isset($this->request->get['filter_customer'])) {
            $filter_customer = $this->request->get['filter_customer'];
        } else {
            $filter_customer = null;
        }
        if (isset($this->request->get['filter_order_status'])) {
            $filter_order_status = $this->request->get['filter_order_status'];
        } else {
            $filter_order_status = null;
        }
        if (isset($this->request->get['filter_verify_status'])) {
            $filter_verify_status = $this->request->get['filter_verify_status'];
        } else {
            $filter_verify_status = null;
        }
        if (isset($this->request->get['filter_is_pay'])) {
            $filter_is_pay = $this->request->get['filter_is_pay'];
        } else {
            $filter_is_pay = '';
        }
        if (isset($this->request->get['filter_is_shelf_order'])) {
            $filter_is_shelf_order = $this->request->get['filter_is_shelf_order'];
        } else {
            $filter_is_shelf_order = '';
        }
        if (isset($this->request->get['filter_total'])) {
            $filter_total = $this->request->get['filter_total'];
        } else {
            $filter_total = null;
        }
        if (isset($this->request->get['filter_date_added'])) {
            $filter_date_added = $this->request->get['filter_date_added'];
        } else {
            $filter_date_added = null;
        }
        if (isset($this->request->get['filter_date_modified'])) {
            $filter_date_modified = $this->request->get['filter_date_modified'];
        } else {
            $filter_date_modified = null;
        }
        if (isset($this->request->get['filter_date_start'])) {
            $filter_date_start = $this->request->get['filter_date_start'];
        } else {
            $filter_date_start = null;
        }
        if (isset($this->request->get['filter_date_end'])) {
            $filter_date_end = $this->request->get['filter_date_end'];
        } else {
            $filter_date_end = null;
        }
        if (isset($this->request->get['filter_logcenter'])) {
            $filter_logcenter = $this->request->get['filter_logcenter'];
        } else {
            $filter_logcenter = null;
        }
        if (isset($this->request->get['filter_recommended_code'])) {
            $filter_recommended_code = $this->request->get['filter_recommended_code'];
        } else {
            $filter_recommended_code = null;
        }
        if (isset($this->request->get['filter_product_code'])) {//订单包含商品（仅限唯一码）
            $filter_product_code = $this->request->get['filter_product_code'];
        } else {
            $filter_product_code = null;
        }
        if (isset($this->request->get['sort'])) {
            $sort = $this->request->get['sort'];
        } else {
            $sort = 'o.order_id';
        }
        if (isset($this->request->get['order'])) {
            $order = $this->request->get['order'];
        } else {
            $order = 'DESC';
        }
        if (isset($this->request->get['page'])) {
            $page = $this->request->get['page'];
        } else {
            $page = 1;
        }
        $filter_data = array(
            'filter_order_id'      => $filter_order_id,
            'filter_customer'	   => $filter_customer,
            'filter_order_status'  => $filter_order_status,
            'filter_verify_status' => $filter_verify_status,
            'filter_total'         => $filter_total,
            'filter_is_pay'		   => $filter_is_pay,
            'filter_is_shelf_order'		   => $filter_is_shelf_order,
            'filter_date_added'    => $filter_date_added,
            'filter_date_modified' => $filter_date_modified,
            'filter_logcenter' 	   => $filter_logcenter,
            'filter_date_start'	   => $filter_date_start,
            'filter_date_end'	   => $filter_date_end,
            'filter_recommended_code'   => $filter_recommended_code,
            'filter_product_code'  => $filter_product_code,
            'sort'                 => $sort,
            'order'                => $order,
        );
        $this->load->model('catalog/category');
        $allCategory = $this->model_catalog_category->getAllCategoryNames();
        $this->load->model('sale/order');
        $results = $this->model_sale_order->getExportOrders($filter_data);
        $bill_array = array(
            '1'=>'未开发票',
            '2'=>'已开发票',
            '0'=>'不需要开发票',
        );
        foreach ($results as $result) {
            $RU = $result['u_fullname'].'('.$result['u_name'].')';
            if($result['product_type'] != 2){
                if (str_pad($result['product_code'], 11, 0) != str_pad($filter_product_code, 11, 0))
                    continue;
                $data[] = array(
                    'order_id'          => $result['order_id'],
                    'customer'          => $result['customer'],
                    'status'            => $result['status'],
                    'total'             => $result['total'],
                    'date_added'        => date($this->language->get('date_format_short'), strtotime($result['date_added'])),
                    'date_modified'     => date($this->language->get('date_format_short'), strtotime($result['date_modified'])),
                    'bill_status'        => $bill_array[$result['bill_status']],
                    'recommended_code'    => $result['recommended_code'],
                    'recommended_user'  => $RU,
                    'vendor_name'        => $result['vendor_name'],
                    'product_name'        => $result['product_name'],
                    'product_code'                => $result['product_code'],
                    'sku'                => $result['sku'],
                    'shipping_country'    => $result['shipping_country'],
                    'shipping_zone'     => $result['shipping_zone'],
                    'model'                => $result['model'],
                    'quantity'            => $result['quantity'],
                    'lack_quantity'     => $result['lack_quantity'],
                    'price'                => $result['price'],
                    'pprice'                => $result['pprice'],
                    'cd_name'            => $result['cd_name'],
                    'telephone'            => $result['telephone'],
                    'ship_status'        => $result['ship_status']?'已发货':'未发货',
                    'shipping_address'    => $result['shipping_address'],
                    'is_pay'             => $result['is_pay']?'已付款':'未付款',
                    'payment_method'    => $result['payment_method'],
                    'payment_company'    => $result['payment_company'],
                    'paid_time'         => $result['paid_time'],
                    'auditted_time'     => $result['auditted_time'],
                    'delivered_time'    => $result['delivered_time'],
                    'completed_time'    => $result['completed_time'],
                    'out_time'          => $result['out_time'],
                    'cta_day_times' => !empty($result['date_added'])&&!empty($result['auditted_time'])?(floor((strtotime($result['auditted_time'])-strtotime($result['date_added']))/86400)):'',
                    'ctc_day_times' => !empty($result['date_added'])&&!empty($result['completed_time'])?(floor((strtotime($result['completed_time'])-strtotime($result['date_added']))/86400)):'',
                    'product_cost'      => $result['product_cost'],
                    'profit'            => (round(floatval(($result['price'] - $result['product_cost'])/$result['product_cost']),2)*100).'%',
                    'class1Name'        => $allCategory[$result['product_class1']],
                    'class2Name'        => $allCategory[$result['product_class2']],
                    'class3Name'        => $allCategory[$result['product_class3']],
                );
            }else{
                $sub_results = $this->model_sale_order->getExportCombineProduct($result['order_product_id']);

                $exist_array = array();

                foreach($sub_results as $sub_result){
                    if ((str_pad($result['product_code'], 11, 0) != str_pad($filter_product_code, 11, 0)) && (str_pad($sub_result['product_code'], 11, 0) != str_pad($filter_product_code, 11, 0)))
                        continue;
                    $data[] = array(
                        'order_id'          => $result['order_id'],
                        'customer'          => $result['customer'],
                        'status'            => $result['status'],
                        'total'             => $sub_result['total'],
                        'date_added'        => date($this->language->get('date_format_short'), strtotime($result['date_added'])),
                        'date_modified'     => date($this->language->get('date_format_short'), strtotime($result['date_modified'])),
                        'bill_status'        => $bill_array[$result['bill_status']],
                        'recommended_code'    => $result['recommended_code'],
                        'recommended_user'  => $RU,
                        'vendor_name'        => $sub_result['vsname'],
                        'product_name'        => $sub_result['pdname'].'('.$result['product_name'].')',
                        'product_code'                => $sub_result['product_code'],
                        'sku'                => $sub_result['sku'],
                        'shipping_country'    => $result['shipping_country'],
                        'shipping_zone'     => $result['shipping_zone'],
                        'model'                => $sub_result['model'],
                        'quantity'            => $sub_result['quantity'],
                        'lack_quantity'     => $sub_result['lack_quantity'],
                        'price'                => $sub_result['price'],
                        'pprice'                => $sub_result['pprice'],
                        'cd_name'            => $sub_result['cdname'],
                        'telephone'            => $result['telephone'],
                        'ship_status'        => $result['ship_status']?'已发货':'未发货',
                        'shipping_address'    => $result['shipping_address'],
                        'is_pay'             => $result['is_pay']?'已付款':'未付款',
                        'payment_method'    => $result['payment_method'],
                        'payment_company'    => $result['payment_company'],
                        'paid_time'         => $result['paid_time'],
                        'auditted_time'     => $result['auditted_time'],
                        'delivered_time'    => $result['delivered_time'],
                        'completed_time'    => $result['completed_time'],
                        'out_time'          => $result['out_time'],
                        'cta_day_times' => !empty($result['date_added'])&&!empty($result['auditted_time'])?(floor((strtotime($result['auditted_time'])-strtotime($result['date_added']))/86400)):'',
                        'ctc_day_times' => !empty($result['date_added'])&&!empty($result['completed_time'])?(floor((strtotime($result['completed_time'])-strtotime($result['date_added']))/86400)):'',
                        'product_cost'      => $sub_result['product_cost'],
                        'profit'            => (round(floatval(($sub_result['price'] - $sub_result['product_cost'])/$sub_result['product_cost']),2)*100).'%',
                    'class1Name'        => $allCategory[$result['product_class1']],
                    'class2Name'        => $allCategory[$result['product_class2']],
                    'class3Name'        => $allCategory[$result['product_class3']],
                    );

                }
            }
        }
        $this->load->library('PHPExcel/PHPExcel');
        $objPHPExcel = new PHPExcel();
        $objProps = $objPHPExcel->getProperties();
        $objProps->setCreator("Think-tec");
        $objProps->setLastModifiedBy("Think-tec");
        $objProps->setTitle("Think-tec Contact");
        $objProps->setSubject("Think-tec Contact Data");
        $objProps->setDescription("Think-tec Contact Data");
        $objProps->setKeywords("Think-tec Contact");
        $objProps->setCategory("Think-tec");
        $objPHPExcel->setActiveSheetIndex(0);
        $objActSheet = $objPHPExcel->getActiveSheet();

        $objActSheet->setTitle('Sheet1');
        $col_idx = 'A';
        $headers = array( '订单日期',  '订单ID',  '会员手机号','会员信息','收货超市','商品大类','商品中类','商品小类','商品名称',     '品牌产商', '商品编码',    '条形码','型号',    '数量','缺货数量',     '单品价格','单品小计','单品成本','参考零售价','单品毛利率','订单状态',  '开票状态',    '邀请码','业务员',           '省市',              '市县','详细地址','分类','商品发货状态','付款状态','付款方式','支付时间','审核时间','出库时间','派送时间','完成时间','审核天数','履约天数');
        $row_keys = array('date_added','order_id','telephone', 'customer','payment_company','class1Name','class2Name','class3Name','product_name','vendor_name', 'product_code', 'sku',     'model','quantity','lack_quantity','price',  'total', 'product_cost','pprice','profit',  'status','bill_status','recommended_code','recommended_user','shipping_country','shipping_zone','shipping_address','cd_name','ship_status','is_pay','payment_method','paid_time','auditted_time','out_time','delivered_time','completed_time','cta_day_times','ctc_day_times');
        foreach ($headers as $header) {
          $objActSheet->setCellValue($col_idx++.'1', $header);
        }
        //添加物流信息
        $i = 2;
        foreach ($data as $rlst) {
          $col_idx = 'A';
          foreach ($row_keys as $rk) {
            $objActSheet->setCellValueExplicit($col_idx++.$i, $rlst[$rk], PHPExcel_Cell_DataType::TYPE_STRING);
          }
          $i++;
        }

        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');

        ob_end_clean();
        // Redirect output to a client’s web browser (Excel2007)
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="order_'.date('Y-m-d',time()).'.xlsx"');
        header('Cache-Control: max-age=0');
        // If you're serving to IE 9, then the following may be needed
        header('Cache-Control: max-age=1');

        // If you're serving to IE over SSL, then the following may be needed
        header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
        header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header ('Pragma: public'); // HTTP/1.0
        $objWriter->save('php://output');
        exit;
    }

    //页面按钮：导出订单
	public function exportLists(){

		if (isset($this->request->get['filter_order_id'])) {
			$filter_order_id = $this->request->get['filter_order_id'];
		} else {
			$filter_order_id = null;
		}

		if (isset($this->request->get['filter_customer'])) {
			$filter_customer = $this->request->get['filter_customer'];
		} else {
			$filter_customer = null;
		}

		if (isset($this->request->get['filter_order_status'])) {
			$filter_order_status = $this->request->get['filter_order_status'];
		} else {
			$filter_order_status = null;
		}

		if (isset($this->request->get['filter_verify_status'])) {
			$filter_verify_status = $this->request->get['filter_verify_status'];
		} else {
			$filter_verify_status = null;
		}

		if (isset($this->request->get['filter_is_pay'])) {
			$filter_is_pay = $this->request->get['filter_is_pay'];
		} else {
			$filter_is_pay = '';
		}
		if (isset($this->request->get['filter_is_shelf_order'])) {
			$filter_is_shelf_order = $this->request->get['filter_is_shelf_order'];
		} else {
			$filter_is_shelf_order = 3;
		}

		if (isset($this->request->get['filter_total'])) {
			$filter_total = $this->request->get['filter_total'];
		} else {
			$filter_total = null;
		}

		if (isset($this->request->get['filter_date_added'])) {
			$filter_date_added = $this->request->get['filter_date_added'];
		} else {
			$filter_date_added = null;
		}

		if (isset($this->request->get['filter_date_modified'])) {
			$filter_date_modified = $this->request->get['filter_date_modified'];
		} else {
			$filter_date_modified = null;
		}

		if (isset($this->request->get['filter_date_start'])) {
			$filter_date_start = $this->request->get['filter_date_start'];
		} else {
			$filter_date_start = null;
		}

		if (isset($this->request->get['filter_date_end'])) {
			$filter_date_end = $this->request->get['filter_date_end'];
		} else {
			$filter_date_end = null;
		}

		if (isset($this->request->get['filter_logcenter'])) {
			$filter_logcenter = $this->request->get['filter_logcenter'];
		} else {
			$filter_logcenter = null;
		}

		if (isset($this->request->get['filter_recommended_code'])) {
			$filter_recommended_code = $this->request->get['filter_recommended_code'];
		} else {
			$filter_recommended_code = null;
		}

        if (isset($this->request->get['filter_product_code'])) {//订单包含商品（仅限唯一码）
            $filter_product_code = $this->request->get['filter_product_code'];
        } else {
            $filter_product_code = null;
        }

		if (isset($this->request->get['sort'])) {
			$sort = $this->request->get['sort'];
		} else {
			$sort = 'o.order_id';
		}

		if (isset($this->request->get['order'])) {
			$order = $this->request->get['order'];
		} else {
			$order = 'DESC';
		}

		if (isset($this->request->get['page'])) {
			$page = $this->request->get['page'];
		} else {
			$page = 1;
		}
		// var_dump($filter_is_shelf_order);die();
		$filter_data = array(
			'filter_order_id'      => $filter_order_id,
			'filter_customer'	   => $filter_customer,
			'filter_order_status'  => $filter_order_status,
			'filter_verify_status' => $filter_verify_status,
			'filter_total'         => $filter_total,
			'filter_is_pay'		   => $filter_is_pay,
			'filter_is_shelf_order'		   => $filter_is_shelf_order,
			'filter_date_added'    => $filter_date_added,
			'filter_date_modified' => $filter_date_modified,
			'filter_logcenter' 	   => $filter_logcenter,
			'filter_date_start'	   => $filter_date_start,
			'filter_date_end'	   => $filter_date_end,
			'filter_recommended_code'	   => $filter_recommended_code,
            'filter_product_code'  => $filter_product_code,
			'sort'                 => $sort,
			'order'                => $order,
		);
		$this->load->model('catalog/category');
        $allCategory = $this->model_catalog_category->getAllCategoryNames();

        $this->load->model('sale/order');
        $results = $this->model_sale_order->getExportOrders($filter_data);
		$bill_array = array(
			'1'=>'未开发票',
			'2'=>'已开发票',
			'0'=>'不需要开发票',
			);

		foreach ($results as $result) {
            $RU = $result['u_fullname'].'('.$result['u_name'].')';
			if($result['product_type'] != 2){
				$data[] = array(
					'order_id'      	=> $result['order_id'],
					'customer'      	=> $result['customer'],
					'status'        	=> $result['status'],
					'total'         	=> $result['total'],
					'date_added'    	=> date($this->language->get('date_format_short'), strtotime($result['date_added'])),
					'date_modified' 	=> date($this->language->get('date_format_short'), strtotime($result['date_modified'])),
					'bill_status'		=> $bill_array[$result['bill_status']],
					'recommended_code'	=> $result['recommended_code'],
                    'recommended_user'  => $RU,
					'vendor_name'		=> $result['vendor_name'],
					'product_name'		=> $result['product_name'],
					'product_code'				=> $result['product_code'],
					'sku'				=> $result['sku'],
					'shipping_country'	=> $result['shipping_country'],
					'shipping_zone' 	=> $result['shipping_zone'],
					'model'				=> $result['model'],
					'quantity'			=> $result['quantity'],
					'lack_quantity'     => $result['lack_quantity'],
					'price'				=> $result['price'],
					'pprice'				=> $result['pprice'],
					'cd_name'			=> $result['cd_name'],
					'telephone'			=> $result['telephone'],
					'ship_status'		=> $result['ship_status']?'已发货':'未发货',
					'shipping_address'	=> $result['shipping_address'],
					'is_pay' 			=> $result['is_pay']?'已付款':'未付款',
					'payment_method'    => $result['payment_method'],
					'payment_company'    => $result['payment_company'],
					'paid_time'         => $result['paid_time'],
					'auditted_time'     => $result['auditted_time'],
					'delivered_time'    => $result['delivered_time'],
					'completed_time'    => $result['completed_time'],
					'out_time'          => $result['out_time'],
					'cta_day_times' => !empty($result['date_added'])&&!empty($result['auditted_time'])?(floor((strtotime($result['auditted_time'])-strtotime($result['date_added']))/86400)):'',
					'ctc_day_times' => !empty($result['date_added'])&&!empty($result['completed_time'])?(floor((strtotime($result['completed_time'])-strtotime($result['date_added']))/86400)):'',
					'product_cost'      => $result['product_cost'],
					'profit'            => (round(floatval(($result['price'] - $result['product_cost'])/$result['product_cost']),2)*100).'%',
                    'class1Name'        => $allCategory[$result['product_class1']],
                    'class2Name'        => $allCategory[$result['product_class2']],
                    'class3Name'        => $allCategory[$result['product_class3']],
				);
			}else{
				$sub_results = $this->model_sale_order->getExportCombineProduct($result['order_product_id']);

				$exist_array = array();

				foreach($sub_results as $sub_result){

					$data[] = array(
						'order_id'      	=> $result['order_id'],
						'customer'      	=> $result['customer'],
						'status'        	=> $result['status'],
						'total'         	=> $sub_result['total'],
						'date_added'    	=> date($this->language->get('date_format_short'), strtotime($result['date_added'])),
						'date_modified' 	=> date($this->language->get('date_format_short'), strtotime($result['date_modified'])),
						'bill_status'		=> $bill_array[$result['bill_status']],
						'recommended_code'	=> $result['recommended_code'],
                        'recommended_user'  => $RU,
						'vendor_name'		=> $sub_result['vsname'],
						'product_name'		=> $sub_result['pdname'].'('.$result['product_name'].')',
						'product_code'				=> $sub_result['product_code'],
						'sku'				=> $sub_result['sku'],
						'shipping_country'	=> $result['shipping_country'],
						'shipping_zone' 	=> $result['shipping_zone'],
						'model'				=> $sub_result['model'],
						'quantity'			=> $sub_result['quantity'],
						'lack_quantity'     => $sub_result['lack_quantity'],
						'price'				=> $sub_result['price'],
						'pprice'				=> $sub_result['pprice'],
						'cd_name'			=> $sub_result['cdname'],
						'telephone'			=> $result['telephone'],
						'ship_status'		=> $result['ship_status']?'已发货':'未发货',
						'shipping_address'	=> $result['shipping_address'],
						'is_pay' 			=> $result['is_pay']?'已付款':'未付款',
						'payment_method'    => $result['payment_method'],
						'payment_company'    => $result['payment_company'],
						'paid_time'         => $result['paid_time'],
						'auditted_time'     => $result['auditted_time'],
						'delivered_time'    => $result['delivered_time'],
						'completed_time'    => $result['completed_time'],
						'out_time'          => $result['out_time'],
						'cta_day_times' => !empty($result['date_added'])&&!empty($result['auditted_time'])?(floor((strtotime($result['auditted_time'])-strtotime($result['date_added']))/86400)):'',
						'ctc_day_times' => !empty($result['date_added'])&&!empty($result['completed_time'])?(floor((strtotime($result['completed_time'])-strtotime($result['date_added']))/86400)):'',
						'product_cost'      => $sub_result['product_cost'],
						'profit'            => (round(floatval(($sub_result['price'] - $sub_result['product_cost'])/$sub_result['product_cost']),2)*100).'%',
                    'class1Name'        => $allCategory[$result['product_class1']],
                    'class2Name'        => $allCategory[$result['product_class2']],
                    'class3Name'        => $allCategory[$result['product_class3']],
					);

				}
			}
		}
	    $this->load->library('PHPExcel/PHPExcel');
	    $objPHPExcel = new PHPExcel();
	    $objProps = $objPHPExcel->getProperties();
	    $objProps->setCreator("Think-tec");
	    $objProps->setLastModifiedBy("Think-tec");
	    $objProps->setTitle("Think-tec Contact");
	    $objProps->setSubject("Think-tec Contact Data");
	    $objProps->setDescription("Think-tec Contact Data");
	    $objProps->setKeywords("Think-tec Contact");
	    $objProps->setCategory("Think-tec");
	    $objPHPExcel->setActiveSheetIndex(0);
	    $objActSheet = $objPHPExcel->getActiveSheet();

	    $objActSheet->setTitle('Sheet1');
	    $col_idx = 'A';
	    $headers = array( '订单日期',  '订单ID',  '会员手机号','会员信息','收货超市','商品大类','商品中类','商品小类','商品名称',	 '品牌产商', '商品编码',	'条形码','型号',	'数量','缺货数量',	 '单品价格','单品小计','单品成本','参考零售价','单品毛利率','订单状态',  '开票状态',	'邀请码','业务员',		   '省市',			  '市县','详细地址','分类','商品发货状态','付款状态','付款方式','支付时间','审核时间','出库时间','派送时间','完成时间','审核天数','履约天数');
	    $row_keys = array('date_added','order_id','telephone', 'customer','payment_company','class1Name','class2Name','class3Name','product_name','vendor_name', 'product_code', 'sku',	 'model','quantity','lack_quantity','price',  'total', 'product_cost','pprice','profit',  'status','bill_status','recommended_code','recommended_user','shipping_country','shipping_zone','shipping_address','cd_name','ship_status','is_pay','payment_method','paid_time','auditted_time','out_time','delivered_time','completed_time','cta_day_times','ctc_day_times');
	    foreach ($headers as $header) {
	      $objActSheet->setCellValue($col_idx++.'1', $header);
	    }
	    //添加物流信息
	    $i = 2;
	    foreach ($data as $rlst) {
	      $col_idx = 'A';
	      foreach ($row_keys as $rk) {
	        $objActSheet->setCellValueExplicit($col_idx++.$i, $rlst[$rk], PHPExcel_Cell_DataType::TYPE_STRING);
	      }
	      $i++;
	    }

	    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');

	    ob_end_clean();
	    // Redirect output to a client’s web browser (Excel2007)
	    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
	    header('Content-Disposition: attachment;filename="order_'.date('Y-m-d',time()).'.xlsx"');
	    header('Cache-Control: max-age=0');
	    // If you're serving to IE 9, then the following may be needed
	    header('Cache-Control: max-age=1');

	    // If you're serving to IE over SSL, then the following may be needed
	    header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
	    header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
	    header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
	    header ('Pragma: public'); // HTTP/1.0
	    $objWriter->save('php://output');
	    exit;
  }

    //页面按钮：导出汇总订单
  public function exportCollect(){
  	if (isset($this->request->get['filter_order_id'])) {
			$filter_order_id = $this->request->get['filter_order_id'];
		} else {
			$filter_order_id = null;
		}

		if (isset($this->request->get['filter_customer'])) {
			$filter_customer = $this->request->get['filter_customer'];
		} else {
			$filter_customer = null;
		}

		if (isset($this->request->get['filter_order_status'])) {
			$filter_order_status = $this->request->get['filter_order_status'];
		} else {
			$filter_order_status = null;
		}

		if (isset($this->request->get['filter_verify_status'])) {
			$filter_verify_status = $this->request->get['filter_verify_status'];
		} else {
			$filter_verify_status = null;
		}

		if (isset($this->request->get['filter_total'])) {
			$filter_total = $this->request->get['filter_total'];
		} else {
			$filter_total = null;
		}

		if (isset($this->request->get['filter_is_pay'])) {
			$filter_is_pay = $this->request->get['filter_is_pay'];
		} else {
			$filter_is_pay = '';
		}

		if (isset($this->request->get['filter_is_shelf_order'])) {
			$filter_is_shelf_order = $this->request->get['filter_is_shelf_order'];
		} else {
			$filter_is_shelf_order = '';
		}

		if (isset($this->request->get['filter_date_added'])) {
			$filter_date_added = $this->request->get['filter_date_added'];
		} else {
			$filter_date_added = null;
		}

		if (isset($this->request->get['filter_date_modified'])) {
			$filter_date_modified = $this->request->get['filter_date_modified'];
		} else {
			$filter_date_modified = null;
		}

		if (isset($this->request->get['filter_date_start'])) {
			$filter_date_start = $this->request->get['filter_date_start'];
		} else {
			$filter_date_start = null;
		}

		if (isset($this->request->get['filter_date_end'])) {
			$filter_date_end = $this->request->get['filter_date_end'];
		} else {
			$filter_date_end = null;
		}

		if (isset($this->request->get['filter_logcenter'])) {
			$filter_logcenter = $this->request->get['filter_logcenter'];
		} else {
			$filter_logcenter = null;
		}

		if (isset($this->request->get['filter_recommended_code'])) {
			$filter_recommended_code = $this->request->get['filter_recommended_code'];
		} else {
			$filter_recommended_code = null;
		}

        if (isset($this->request->get['filter_product_code'])) {//订单包含商品（仅限唯一码）
            $filter_product_code = $this->request->get['filter_product_code'];
        } else {
            $filter_product_code = null;
        }

		if (isset($this->request->get['sort'])) {
			$sort = $this->request->get['sort'];
		} else {
			$sort = 'o.order_id';
		}

		if (isset($this->request->get['order'])) {
			$order = $this->request->get['order'];
		} else {
			$order = 'DESC';
		}

		$filter_data = array(
			'filter_order_id'      => $filter_order_id,
			'filter_customer'	   => $filter_customer,
			'filter_order_status'  => $filter_order_status,
			'filter_verify_status' => $filter_verify_status,
			'filter_total'         => $filter_total,
			'filter_date_added'    => $filter_date_added,
			'filter_date_modified' => $filter_date_modified,
			'filter_logcenter' 	   => $filter_logcenter,
			'filter_is_pay'		   => $filter_is_pay,
			'filter_is_shelf_order'		   => $filter_is_shelf_order,
			'filter_date_start'	   => $filter_date_start,
			'filter_date_end'	   => $filter_date_end,
			'filter_recommended_code'	   => $filter_recommended_code,
            'filter_product_code'  => $filter_product_code,
			'sort'                 => $sort,
			'order'                => $order,
		);
		$this->load->model('sale/order');
		$this->load->model('sale/stock_out');

		$results = $this->model_sale_order->getOrders($filter_data);
        //订单的时间点更新有问题，直接获取基于订单编号的出库单相关时间，入库单最晚创建时间和入库单最晚签收时间
        $soList = $this->model_sale_stock_out->getDateRangeGroupByOrderId();
		foreach ($results as $result) {
            $firstCtaDayTimes = floor((time()-strtotime($result['date_added']))/86400);
            $lastCtaDayTimes = '';
            $firstCtcDayTimes = '';
            $lastCtcDayTimes = '';
            if (array_key_exists($result['order_id'], $soList)) {
                $firstCtaDayTimes = floor((strtotime($soList[$result['order_id']]['firstDateAdded'])-strtotime($result['date_added']))/86400);
                $lastCtaDayTimes = floor((strtotime($soList[$result['order_id']]['lastDateAdded'])-strtotime($result['date_added']))/86400);
                if ($soList[$result['order_id']]['firstReceiveDate']) {
                    $firstCtcDayTimes = floor((strtotime($soList[$result['order_id']]['firstReceiveDate'])-strtotime($result['date_added']))/86400);
                }
                if ($soList[$result['order_id']]['lastReceiveDate']) {
                    $lastCtcDayTimes = floor((strtotime($soList[$result['order_id']]['lastReceiveDate'])-strtotime($result['date_added']))/86400);
                }
            }
			$save_data[] = array(
				'order_id'              => $result['order_id'],
				'shipping_company'      => $result['shipping_company'],
				'customer'              => $result['customer'],
				'status'                => $result['status'],
				'verify_status'         => intval($result['verify_status'])?(intval($result['verify_status'])==1?'已审核(缺货)':'已审核'):'未审核',
				'shipping_zone'         => $result['shipping_zone'],
				'shop_type'         => getShopTypes()[$result['shop_type']],

				'shelf_order_id'		=> $result['shelf_order_id'],
				'is_shelf_order'		=> $result['shelf_order_id']?'货架客户':'普通客户',
				'shipping_country'      => $result['shipping_country'],
                'shipping_address'      => $result['shipping_address'],
				'recommended_code'      => $result['recommended_code'],
				'recommended_name'      => $result['recommended_name'],
				'bill_status'	        => $bill_array[$result['bill_status']],
				'total'                 => number_format($result['total'],2,'.',''),
				'value'                 => number_format($result['value'],2,'.',''),
				'date_added'            => date('Y-m-d h:i', strtotime($result['date_added'])),
				'is_pay' 		        => $result['is_pay']?'已付款':'未付款',
				'payment_method'        => $result['payment_method'],
				'paid_time'             => $result['paid_time'],
				'auditted_time'         => $soList[$result['order_id']]['firstDateAdded'],//$result['auditted_time'],//审核时间
				'out_time'              => $soList[$result['order_id']]['firstOutDate'],//$result['out_time'],//出库时间
                'first_cta_day_times'   => $firstCtaDayTimes,
                'last_cta_day_times'    => $lastCtaDayTimes,
                'first_ctc_day_times'   => $firstCtcDayTimes,
                'last_ctc_day_times'    => $lastCtcDayTimes,
				'delivered_time'        => $soList[$result['order_id']]['firstDeliverDate'],//$result['delivered_time'],//派送时间
				'completed_time'        => ($result['completed_time'])?$soList[$result['order_id']]['firstReceiveDate']:'',//$result['completed_time'],//完成时间
                'logcenter_name'        => $result['logcenter_name'],
                'first_so_rate'         => $result['first_stock_out_rate'],
                'final_so_rate'         => $result['final_stock_out_rate'],
			);
		}
		// var_dump($save_data);die()
    $exportCols = array(
        'order_id'              => '订单号',
        'shop_type'              => '终端规模',
        'is_shelf_order'              => '客户类型',
        'customer'              => '会员',
        'status'                => '状态',
        'verify_status'         => '审核状态',
        'value'                 => '原价单品小计',
        'total'                 => '单品小计',
        'date_added'            => '下单日期',
        'bill_status'           => '开票状态',
        'shipping_company'      => '超市名称',
        'recommended_code'      => '邀请码',
        'recommended_name'      => '客户经理姓名',
        'shipping_country'      => '省市',
        'shipping_zone'         => '市县',
        'shipping_address'      => '地址',
        'is_pay'                => '付款状态',
        'payment_method'        => '支付方式',
        'paid_time'             => '支付时间',
        'auditted_time'         => '审核时间',
        'out_time'              => '出库时间',
        'delivered_time'        => '派送时间',
        'completed_time'        => '完成时间',
        'first_cta_day_times'   => '最快审核天数',
        'last_cta_day_times'    => '最慢审核天数',
        'first_ctc_day_times'   => '最快履约天数',
        'last_ctc_day_times'    => '最慢履约天数',
        'logcenter_name'        => '配送中心',
        'first_so_rate'         => '订单满足率',
        'final_so_rate'         => '订单履约率',
    );

    $this->load->helper('export');
    prepareDownloadExcel($save_data, array_values($exportCols), array_keys($exportCols), 'Orders');
  }

   //页面按钮：导出组合商品销售
	public function exportConbin(){

		if (isset($this->request->get['filter_order_id'])) {
			$filter_order_id = $this->request->get['filter_order_id'];
		} else {
			$filter_order_id = null;
		}

		if (isset($this->request->get['filter_customer'])) {
			$filter_customer = $this->request->get['filter_customer'];
		} else {
			$filter_customer = null;
		}

		if (isset($this->request->get['filter_order_status'])) {
			$filter_order_status = $this->request->get['filter_order_status'];
		} else {
			$filter_order_status = null;
		}

		if (isset($this->request->get['filter_verify_status'])) {
			$filter_verify_status = $this->request->get['filter_verify_status'];
		} else {
			$filter_verify_status = null;
		}

		if (isset($this->request->get['filter_is_pay'])) {
			$filter_is_pay = $this->request->get['filter_is_pay'];
		} else {
			$filter_is_pay = '';
		}

		if (isset($this->request->get['filter_is_shelf_order'])) {
			$filter_is_shelf_order = $this->request->get['filter_is_shelf_order'];
		} else {
			$filter_is_shelf_order = '';
		}

		if (isset($this->request->get['filter_total'])) {
			$filter_total = $this->request->get['filter_total'];
		} else {
			$filter_total = null;
		}

		if (isset($this->request->get['filter_date_added'])) {
			$filter_date_added = $this->request->get['filter_date_added'];
		} else {
			$filter_date_added = null;
		}

		if (isset($this->request->get['filter_date_modified'])) {
			$filter_date_modified = $this->request->get['filter_date_modified'];
		} else {
			$filter_date_modified = null;
		}

		if (isset($this->request->get['filter_date_start'])) {
			$filter_date_start = $this->request->get['filter_date_start'];
		} else {
			$filter_date_start = null;
		}

		if (isset($this->request->get['filter_date_end'])) {
			$filter_date_end = $this->request->get['filter_date_end'];
		} else {
			$filter_date_end = null;
		}

		if (isset($this->request->get['filter_logcenter'])) {
			$filter_logcenter = $this->request->get['filter_logcenter'];
		} else {
			$filter_logcenter = null;
		}

		if (isset($this->request->get['filter_recommended_code'])) {
			$filter_recommended_code = $this->request->get['filter_recommended_code'];
		} else {
			$filter_recommended_code = null;
		}

		if (isset($this->request->get['sort'])) {
			$sort = $this->request->get['sort'];
		} else {
			$sort = 'o.order_id';
		}

		if (isset($this->request->get['order'])) {
			$order = $this->request->get['order'];
		} else {
			$order = 'DESC';
		}

		if (isset($this->request->get['page'])) {
			$page = $this->request->get['page'];
		} else {
			$page = 1;
		}

		$filter_data = array(
			'filter_order_id'      => $filter_order_id,
			'filter_customer'	   => $filter_customer,
			'filter_order_status'  => $filter_order_status,
			'filter_verify_status' => $filter_verify_status,
			'filter_total'         => $filter_total,
			'filter_is_shelf_order'		   => $filter_is_shelf_order,
			'filter_is_pay'		   => $filter_is_pay,
			'filter_date_added'    => $filter_date_added,
			'filter_date_modified' => $filter_date_modified,
			'filter_logcenter' 	   => $filter_logcenter,
			'filter_date_start'	   => $filter_date_start,
			'filter_date_end'	   => $filter_date_end,
			'filter_recommended_code'	   => $filter_recommended_code,
			'sort'                 => $sort,
			'order'                => $order,
			'product_type'                => 2,
		);
		$this->load->model('catalog/category');
        $allCategory = $this->model_catalog_category->getAllCategoryNames();

        $this->load->model('sale/order');
        $results = $this->model_sale_order->getExportOrders($filter_data);
		$bill_array = array(
			'1'=>'未开发票',
			'2'=>'已开发票',
			'0'=>'不需要开发票',
			);

		foreach ($results as $result) {
            $RU = $result['u_fullname'].'('.$result['u_name'].')';
			if($result['product_type'] == 2){
				$data[] = array(
					'order_id'      	=> $result['order_id'],
					'customer'      	=> $result['customer'],
					'status'        	=> $result['status'],
					'total'         	=> $result['total'],
					'date_added'    	=> date($this->language->get('date_format_short'), strtotime($result['date_added'])),
					'date_modified' 	=> date($this->language->get('date_format_short'), strtotime($result['date_modified'])),
					'bill_status'		=> $bill_array[$result['bill_status']],
					'recommended_code'	=> $result['recommended_code'],
                    'recommended_user'  => $RU,
					'vendor_name'		=> $result['vendor_name'],
					'product_name'		=> $result['product_name'],
					'product_code'				=> $result['product_code'],
					'sku'				=> $result['sku'],
					'shipping_country'	=> $result['shipping_country'],
					'shipping_zone' 	=> $result['shipping_zone'],
					'model'				=> $result['model'],
					'quantity'			=> $result['quantity'],
					'lack_quantity'     => $result['lack_quantity'],
					'price'				=> $result['price'],
					'pprice'				=> $result['pprice'],
					'cd_name'			=> $result['cd_name'],
					'telephone'			=> $result['telephone'],
					'ship_status'		=> $result['ship_status']?'已发货':'未发货',
					'shipping_address'	=> $result['shipping_address'],
					'is_pay' 			=> $result['is_pay']?'已付款':'未付款',
					'payment_method'    => $result['payment_method'],
					'paid_time'         => $result['paid_time'],
					'auditted_time'     => $result['auditted_time'],
					'delivered_time'    => $result['delivered_time'],
					'completed_time'    => $result['completed_time'],
					'out_time'          => $result['out_time'],
					'cta_day_times' => !empty($result['date_added'])&&!empty($result['auditted_time'])?(floor((strtotime($result['auditted_time'])-strtotime($result['date_added']))/86400)):'',
					'ctc_day_times' => !empty($result['date_added'])&&!empty($result['completed_time'])?(floor((strtotime($result['completed_time'])-strtotime($result['date_added']))/86400)):'',
					'product_cost'      => $result['product_cost'],
					'profit'            => (round(floatval(($result['price'] - $result['product_cost'])/$result['product_cost']),2)*100).'%',
                    'class1Name'        => $allCategory[$result['product_class1']],
                    'class2Name'        => $allCategory[$result['product_class2']],
                    'class3Name'        => $allCategory[$result['product_class3']],
				);
			}

		}
	    $this->load->library('PHPExcel/PHPExcel');
	    $objPHPExcel = new PHPExcel();
	    $objProps = $objPHPExcel->getProperties();
	    $objProps->setCreator("Think-tec");
	    $objProps->setLastModifiedBy("Think-tec");
	    $objProps->setTitle("Think-tec Contact");
	    $objProps->setSubject("Think-tec Contact Data");
	    $objProps->setDescription("Think-tec Contact Data");
	    $objProps->setKeywords("Think-tec Contact");
	    $objProps->setCategory("Think-tec");
	    $objPHPExcel->setActiveSheetIndex(0);
	    $objActSheet = $objPHPExcel->getActiveSheet();

	    $objActSheet->setTitle('Sheet1');
	    $col_idx = 'A';
	    $headers = array( '订单日期',  '订单ID',  '会员手机号','会员信息','商品大类','商品中类','商品小类','商品名称',	 '品牌产商', '商品编码',	'条形码','型号',	'数量','缺货数量',	 '单品价格','单品小计','单品成本','参考零售价','单品毛利率','订单状态',  '开票状态',	'邀请码','业务员',		   '省市',			  '市县','详细地址','分类','商品发货状态','付款状态','付款方式','支付时间','审核时间','出库时间','派送时间','完成时间','审核天数','履约天数');
	    $row_keys = array('date_added','order_id','telephone', 'customer','class1Name','class2Name','class3Name','product_name','vendor_name', 'product_code', 'sku',	 'model','quantity','lack_quantity','price',  'total', 'product_cost','pprice','profit',  'status','bill_status','recommended_code','recommended_user','shipping_country','shipping_zone','shipping_address','cd_name','ship_status','is_pay','payment_method','paid_time','auditted_time','out_time','delivered_time','completed_time','cta_day_times','ctc_day_times');
	    foreach ($headers as $header) {
	      $objActSheet->setCellValue($col_idx++.'1', $header);
	    }
	    //添加物流信息
	    $i = 2;
	    foreach ($data as $rlst) {
	      $col_idx = 'A';
	      foreach ($row_keys as $rk) {
	        $objActSheet->setCellValueExplicit($col_idx++.$i, $rlst[$rk], PHPExcel_Cell_DataType::TYPE_STRING);
	      }
	      $i++;
	    }

	    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');

	    ob_end_clean();
	    // Redirect output to a client’s web browser (Excel2007)
	    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
	    header('Content-Disposition: attachment;filename="order_'.date('Y-m-d',time()).'.xlsx"');
	    header('Cache-Control: max-age=0');
	    // If you're serving to IE 9, then the following may be needed
	    header('Cache-Control: max-age=1');

	    // If you're serving to IE over SSL, then the following may be needed
	    header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
	    header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
	    header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
	    header ('Pragma: public'); // HTTP/1.0
	    $objWriter->save('php://output');
	    exit;
  }
  public function exportOrderDetails(){
  	$order_id = I('get.order_id');
  	if(!$order_id){
  		$order_id = 0;
  	}

  	$this->load->model('sale/order');
  	$order_info = $this->model_sale_order->getOrder($order_id);
  	$products = $this->model_sale_order->getOrderProducts($order_id);

  	$this->load->library('PHPExcel/PHPExcel');
    $objReader = PHPExcel_IOFactory::createReader('Excel5');
    $objPHPExcel = $objReader->load(DIR_SYSTEM . "template/sale_tpl.xls");

    $objPHPExcel->getProperties()->setCreator("Think-tec")
               ->setLastModifiedBy("Think-tec")
               ->setTitle("Bai Huo Zhan SC")
               ->setSubject("Bai Huo Zhan SC")
               ->setDescription("Bai Huo Zhan SC")
               ->setKeywords("Bai Huo Zhan, Think-tec")
               ->setCategory("Think-tec");
    $is_pay = $order_info['is_pay']?'已付款':'未付款';
    $objActSheet = $objPHPExcel->getActiveSheet();
    $objActSheet->setCellValue('A1', '百货栈销售单('.$is_pay.')');
    $objActSheet->setCellValue('I1', $order_info['order_id']);
    $objActSheet->setCellValue('B2', $order_info['payment_company']);
    $shipping_address = $order_info['shipping_country'].$order_info['shipping_zone'].$order_info['shipping_city'].$order_info['shipping_address'];
    $objActSheet->setCellValue('E2', $shipping_address);
    $objActSheet->setCellValue('B3', $order_info['shipping_fullname']);
    $objActSheet->setCellValue('E3', $order_info['shipping_telephone']);
    $objActSheet->setCellValue('B4', $order_info['order_id']);
    $objActSheet->setCellValue('E4', $order_info['date_added']);

    $objPHPExcel->getActiveSheet()->insertNewRowBefore(6, count($products));
    $count = 0;
    $row_num = 5;
    $product_num = 0;
    $sum_total = 0;
    foreach ($products as $key => $product) {
      $product_num+=$product['quantity'];
      $sum_total+=$product['total'];
      $objActSheet->setCellValue('A'.$row_num, $product['order_ids']);
      $objActSheet->setCellValue('B'.$row_num, $product['name']);
      $objActSheet->mergeCells("B".$row_num.":D".$row_num);
      $objActSheet->setCellValue('E'.$row_num, $product['sku']);
      $objActSheet->setCellValue('F'.$row_num, $product['model']);
      $objActSheet->setCellValue('G'.$row_num, $product['quantity']);
      $objActSheet->setCellValue('H'.$row_num, $product['price']);
      $objActSheet->setCellValue('I'.$row_num, $product['total']);
      $row_num++;
    }
    $row_num+=2;
    $objActSheet->setCellValue('G'.$row_num, $product_num);
    $objActSheet->setCellValue('I'.$row_num, $sum_total);


    $objActSheet->setTitle('百货栈订单');
    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
    ob_end_clean();
    // Redirect output to a client’s web browser (Excel2007)
    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    header('Content-Disposition: attachment;filename="SALES_BHZ_'.date('Y-m-d-H-i',time()).'.xls"');
    header('Cache-Control: max-age=0');
    // If you're serving to IE 9, then the following may be needed
    header('Cache-Control: max-age=1');
    // If you're serving to IE over SSL, then the following may be needed
    header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
    header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
    header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
    header ('Pragma: public'); // HTTP/1.0
    $objWriter->save('php://output');
    exit;
  }

  /*编辑商品订单*/
  public function editOrder(){
  	$this->load->model('sale/order');

		if (isset($this->request->get['order_id'])) {
			$order_id = $this->request->get['order_id'];
		} else {
			$order_id = 0;
		}
		if ( $_SERVER['REQUEST_METHOD'] === 'GET' ){
		$order_info = $this->model_sale_order->getOrder($order_id);
		// var_dump($order_info);

		if ($order_info) {
			$this->load->language('sale/order');

			$this->document->setTitle($this->language->get('heading_edit'));

			$data['heading_edit'] = $this->language->get('heading_edit');
			$data['text_ip_add'] = sprintf($this->language->get('text_ip_add'), $this->request->server['REMOTE_ADDR']);
			$data['text_order_detail'] = $this->language->get('text_order_detail');
			$data['text_customer_detail'] = $this->language->get('text_customer_detail');
			$data['text_option'] = $this->language->get('text_option');
			$data['text_store'] = $this->language->get('text_store');
			$data['text_date_added'] = $this->language->get('text_date_added');
			$data['text_payment_method'] = $this->language->get('text_payment_method');
			$data['text_shipping_method'] = $this->language->get('text_shipping_method');
			$data['text_customer'] = $this->language->get('text_customer');
			$data['text_customer_group'] = $this->language->get('text_customer_group');
			$data['text_email'] = $this->language->get('text_email');
			$data['text_telephone'] = $this->language->get('text_telephone');
			$data['text_is_invoice_added'] = $this->language->get('text_is_invoice_added');
			$data['text_is_invoice_removed'] = $this->language->get('text_is_invoice_removed');
			$data['text_is_invoice_passed'] = $this->language->get('text_is_invoice_passed');
			$data['text_invoice'] = $this->language->get('text_invoice');
			$data['text_is_invoice'] = $this->language->get('text_is_invoice');
			$data['text_reward'] = $this->language->get('text_reward');
			$data['text_affiliate'] = $this->language->get('text_affiliate');
			$data['text_order'] = sprintf($this->language->get('text_order'), $this->request->get['order_id']);
			$data['text_payment_address'] = $this->language->get('text_payment_address');
			$data['text_shipping_address'] = $this->language->get('text_shipping_address');
			$data['text_comment'] = $this->language->get('text_comment');

			$data['text_account_custom_field'] = $this->language->get('text_account_custom_field');
			$data['text_payment_custom_field'] = $this->language->get('text_payment_custom_field');
			$data['text_shipping_custom_field'] = $this->language->get('text_shipping_custom_field');
			$data['text_browser'] = $this->language->get('text_browser');
			$data['text_ip'] = $this->language->get('text_ip');
			$data['text_forwarded_ip'] = $this->language->get('text_forwarded_ip');
			$data['text_user_agent'] = $this->language->get('text_user_agent');
			$data['text_accept_language'] = $this->language->get('text_accept_language');

			$data['text_history'] = $this->language->get('text_history');
			$data['text_history_add'] = $this->language->get('text_history_add');
			$data['text_loading'] = $this->language->get('text_loading');
			$data['text_shipping_telephone'] = $this->language->get('text_shipping_telephone');

			$data['column_sku'] = $this->language->get('column_sku');
			$data['column_product'] = $this->language->get('column_product');
			$data['column_model'] = $this->language->get('column_model');
			$data['column_quantity'] = $this->language->get('column_quantity');
			$data['column_price'] = $this->language->get('column_price');
			$data['column_total'] = $this->language->get('column_total');

			$data['entry_order_status'] = $this->language->get('entry_order_status');
			$data['entry_notify'] = $this->language->get('entry_notify');
			$data['entry_override'] = $this->language->get('entry_override');
			$data['entry_comment'] = $this->language->get('entry_comment');

			$data['entry_sent_comment_to_all'] = $this->language->get('entry_sent_comment_to_all');
			$data['help_sent_comment_to_all'] = $this->language->get('help_sent_comment_to_all');

			$data['help_override'] = $this->language->get('help_override');

			$data['button_invoice_print'] = $this->language->get('button_invoice_print');
			$data['button_shipping_print'] = $this->language->get('button_shipping_print');
			$data['button_edit'] = $this->language->get('button_edit');
			$data['button_cancel'] = $this->language->get('button_cancel');
			$data['button_generate'] = $this->language->get('button_generate');
			$data['button_is_invoice_add'] = $this->language->get('button_is_invoice_add');
			$data['button_is_invoice_remove'] = $this->language->get('button_is_invoice_remove');
			$data['button_reward_add'] = $this->language->get('button_reward_add');
			$data['button_reward_remove'] = $this->language->get('button_reward_remove');
			$data['button_commission_add'] = $this->language->get('button_commission_add');
			$data['button_commission_remove'] = $this->language->get('button_commission_remove');
			$data['button_history_add'] = $this->language->get('button_history_add');
			$data['button_ip_add'] = $this->language->get('button_ip_add');

			$data['tab_history'] = $this->language->get('tab_history');
			$data['tab_additional'] = $this->language->get('tab_additional');

			/*获取支付方式组*/
			$this->load->model('extension/extension');
			$data['payment_methods'] = $this->model_extension_extension->getExtensions('payment');
			foreach($data['payment_methods'] as $key1 => $value1){
				$codename = $value1['code'];
				$this->load->language('payment/'.$codename);
				$value1["name"] = $this->language->get("heading_title");
				$data['payment_methods'][$key1] = $value1;
			}
			$this->load->language('sale/order');
			/*获取支付方式组*/

			/*获取用户组*/
			$this->load->model('customer/customer_group');
			$data['customer_groups'] = $this->model_customer_customer_group->getCustomerGroups();
			/*获取用户组*/

			$data['token'] = $this->session->data['token'];

			$url = '';

			if (isset($this->request->get['filter_order_id'])) {
				$url .= '&filter_order_id=' . $this->request->get['filter_order_id'];
			}

			if (isset($this->request->get['filter_customer'])) {
				$url .= '&filter_customer=' . urlencode(html_entity_decode($this->request->get['filter_customer'], ENT_QUOTES, 'UTF-8'));
			}

			if (isset($this->request->get['filter_order_status'])) {
				$url .= '&filter_order_status=' . $this->request->get['filter_order_status'];
			}

			if (isset($this->request->get['filter_total'])) {
				$url .= '&filter_total=' . $this->request->get['filter_total'];
			}

			if (isset($this->request->get['filter_date_added'])) {
				$url .= '&filter_date_added=' . $this->request->get['filter_date_added'];
			}

			if (isset($this->request->get['filter_date_modified'])) {
				$url .= '&filter_date_modified=' . $this->request->get['filter_date_modified'];
			}

			if (isset($this->request->get['sort'])) {
				$url .= '&sort=' . $this->request->get['sort'];
			}

			if (isset($this->request->get['order'])) {
				$url .= '&order=' . $this->request->get['order'];
			}

			if (isset($this->request->get['page'])) {
				$url .= '&page=' . $this->request->get['page'];
			}

			$data['breadcrumbs'] = array();

			$data['breadcrumbs'][] = array(
				'text' => $this->language->get('text_home'),
				'href' => $this->url->link('common/dashboard', 'token=' . $this->session->data['token'], 'SSL')
			);

			$data['breadcrumbs'][] = array(
				'text' => $this->language->get('heading_title'),
				'href' => $this->url->link('sale/order', 'token=' . $this->session->data['token'] . $url, 'SSL')
			);
			$data['export'] = $this->url->link('sale/order/export', 'token=' . $this->session->data['token'] . '&order_id=' . (int)$this->request->get['order_id'], 'SSL');
			$data['shipping'] = $this->url->link('sale/order/shipping', 'token=' . $this->session->data['token'] . '&order_id=' . (int)$this->request->get['order_id'], 'SSL');
			$data['invoice'] = $this->url->link('sale/order/invoice', 'token=' . $this->session->data['token'] . '&order_id=' . (int)$this->request->get['order_id'], 'SSL');
			$data['export_order'] = $this->url->link('sale/order/exportOrderDetails', 'token=' . $this->session->data['token'] . '&order_id=' . (int)$this->request->get['order_id'], 'SSL');

			/*编辑订单不改订单号*/
			$data['edit_order'] = $this->url->link('sale/order/editOrder', 'token=' . $this->session->data['token'] . '&order_id=' . (int)$this->request->get['order_id'], 'SSL');
			/*编辑订单不改订单号*/

			$data['edit'] = $this->url->link('sale/order/edit', 'token=' . $this->session->data['token'] . '&order_id=' . (int)$this->request->get['order_id'], 'SSL');
			$data['cancel'] = $this->url->link('sale/order', 'token=' . $this->session->data['token'] . $url, 'SSL');

			$data['order_id'] = $this->request->get['order_id'];

			$data['store_name'] = $order_info['store_name'];
			$data['store_url'] = $order_info['store_url'];

			if ($order_info['invoice_no']) {
				$data['invoice_no'] = $order_info['invoice_prefix'] . $order_info['invoice_no'];
			} else {
				$data['invoice_no'] = '';
			}


			$data['date_added'] = date($this->language->get('date_format_short'), strtotime($order_info['date_added']));
			$data['fullname'] = $order_info['fullname'];

			if ($order_info['customer_id']) {
				$data['customer'] = $this->url->link('customer/customer/edit', 'token=' . $this->session->data['token'] . '&customer_id=' . $order_info['customer_id'], 'SSL');
			} else {
				$data['customer'] = '';
			}

			$this->load->model('customer/customer_group');

			$customer_group_info = $this->model_customer_customer_group->getCustomerGroup($order_info['customer_group_id']);

			if ($customer_group_info) {
				$data['customer_group'] = $customer_group_info['name'];
			} else {
				$data['customer_group'] = '';
			}

			$data['email'] = $order_info['email'];
			$data['telephone'] = $order_info['telephone'];

			$data['is_pay'] = $order_info['is_pay']?'已付款':'未付款';

			$data['shipping_telephone'] = $order_info['shipping_telephone'];

			$data['shipping_method'] = $order_info['shipping_method'];
			$data['recommended_code'] = $order_info['recommended_code'];
			$data['payment_method'] = $order_info['payment_method'];
			$data['payment_code'] = $order_info['payment_code'];

			// Payment Address
			if ($order_info['payment_address_format']) {
				$format = $order_info['payment_address_format'];
			} else {
				$format = '{fullname}' . "\n" . '{company}' . "\n" . '{address}' . "\n" . '{city} {postcode}' . "\n" . '{zone}' . "\n" . '{country}';
			}

			$find = array(
				'{fullname}',
				'{company}',
				'{address}',
				'{city}',
				'{postcode}',
				'{zone}',
				'{zone_code}',
				'{country}'
			);

			$replace = array(
				'fullname' 	=> $order_info['payment_fullname'],
				'company'   => $order_info['payment_company'],
				'address' 	=> $order_info['payment_address'],
				'city'      => $order_info['payment_city'],
				'postcode'  => $order_info['payment_postcode'],
				'zone'      => $order_info['payment_zone'],
				'zone_code' => $order_info['payment_zone_code'],
				'country'   => $order_info['payment_country']
			);

			$data['payment_address'] = str_replace(array("\r\n", "\r", "\n"), '<br />', preg_replace(array("/\s\s+/", "/\r\r+/", "/\n\n+/"), '<br />', trim(str_replace($find, $replace, $format))));

			// Shipping Address
			if ($order_info['shipping_address_format']) {
				$format = $order_info['shipping_address_format'];
			} else {
				$format = '{fullname}' . "\n" . '{company}' . "\n" . '{address}' . "\n" . '{city} {postcode}' . "\n" . '{zone}' . "\n" . '{country}';
			}

			$find = array(
				'{fullname}',
				'{company}',
				'{address}',
				'{city}',
				'{postcode}',
				'{zone}',
				'{zone_code}',
				'{country}'
			);

			$replace = array(
				'fullname' 	=> $order_info['shipping_fullname'],
				'company'   => $order_info['shipping_company'],
				'address' => $order_info['shipping_address'],
				'city'      => $order_info['shipping_city'],
				'postcode'  => $order_info['shipping_postcode'],
				'zone'      => $order_info['shipping_zone'],
				'zone_code' => $order_info['shipping_zone_code'],
				'country'   => $order_info['shipping_country']
			);

			$data['shipping_address'] = str_replace(array("\r\n", "\r", "\n"), '<br />', preg_replace(array("/\s\s+/", "/\r\r+/", "/\n\n+/"), '<br />', trim(str_replace($find, $replace, $format))));

			// Uploaded files
			$this->load->model('tool/upload');

			$data['products'] = array();

			$this->load->model('catalog/vendor');
			$products = $this->model_sale_order->getOrderProducts($order_id);

			$total_ship_status = 1;
			foreach ($products as $product) {
				$option_data = array();

				$options = $this->model_sale_order->getOrderOptions($order_id, $product['order_product_id']);

			$product_vendor_info = M('vendor')->where(array('vproduct_id'=>$product['product_id']))->field('vendor')->find();
	        if($product_vendor_info) {
	         $product['vendor_id'] = $product_vendor_info['vendor'];
	        }
				$vname = $this->model_catalog_vendor->getVendor($product['vendor_id']);

				foreach ($options as $option) {
					if ($option['type'] != 'file') {
						$option_data[] = array(
							'name'  => $option['name'],
							'value' => $option['value'],
							'type'  => $option['type']
						);
					} else {
						$upload_info = $this->model_tool_upload->getUploadByCode($option['value']);

						if ($upload_info) {
							$option_data[] = array(
								'name'  => $option['name'],
								'value' => $upload_info['name'],
								'type'  => $option['type'],
								'href'  => $this->url->link('tool/upload/download', 'token=' . $this->session->data['token'] . '&code=' . $upload_info['code'], 'SSL')
							);
						}
					}
				}
				$childproducts = NULL;

				if($product['product_type'] == 2){
					$childproducts = $this->model_sale_order->getchildorderproducts($product['order_product_id']);
				}

				foreach($childproducts as $key=>$val){
					// var_dump($val['lack_quantity']);
					// var_dump( $val['sumquan']);
					$childproducts[$key]['needed_quantity'] = $val['lack_quantity'] - $val['sumquan'] < 0?0:$val['lack_quantity'] - $val['sumquan'];
				}

				$data['products'][] = array(
					'order_product_id' => (int)$product['order_product_id'],
					'product_type' => (int)$product['product_type'],
					'childproducts'    => $childproducts,
					'product_id'       => $product['product_id'],
					'sku'    	 	   => $product['sku'],
					'name'    	 	   => $product['name'],
					'vname' 		   => $vname['vendor_name'],
					'model'    		   => $product['model'],
					'option'   		   => $option_data,
					'ship_status'	   => $product['ship_status'],
					'order_ids'	   => $product['order_ids'],
					'sign_quantity'	   => $product['sign_quantity'],
					'quantity'		   => $product['quantity'],
					'price'    		   => $this->currency->format($product['price'] + ($this->config->get('config_tax') ? $product['tax'] : 0), $order_info['currency_code'], $order_info['currency_value']),
					'total'    		   => $this->currency->format($product['total'] + ($this->config->get('config_tax') ? ($product['tax'] * $product['quantity']) : 0), $order_info['currency_code'], $order_info['currency_value']),
					'href'     		   => $this->url->link('catalog/product/edit', 'token=' . $this->session->data['token'] . '&product_id=' . $product['product_id'], 'SSL')
				);
				$total_ship_status *= $product['ship_status'];
			}
			// var_dump($data['products']);

			$data['vouchers'] = array();

			$data['total_ship_status'] = $total_ship_status;
			$vouchers = $this->model_sale_order->getOrderVouchers($order_id);

			foreach ($vouchers as $voucher) {
				$data['vouchers'][] = array(
					'description' => $voucher['description'],
					'amount'      => $this->currency->format($voucher['amount'], $order_info['currency_code'], $order_info['currency_value']),
					'href'        => $this->url->link('sale/voucher/edit', 'token=' . $this->session->data['token'] . '&voucher_id=' . $voucher['voucher_id'], 'SSL')
				);
			}

			$data['totals'] = array();

			$totals = $this->model_sale_order->getOrderTotals($order_id);

			foreach ($totals as $total) {
				$data['totals'][] = array(
					'title' => $total['title'],
					'text'  => $this->currency->format($total['value'], $order_info['currency_code'], $order_info['currency_value']),
				);
			}

			$data['totals'][] = array(
				'title' => '原始价',
				'text' => $this->currency->format($order_info['ori_total'], $order_info['currency_code'], $order_info['currency_value']),
			);

			$data['comment'] = nl2br($order_info['comment']);

			$this->load->model('customer/customer');

			$data['reward'] = $order_info['reward'];

			switch ($order_info['bill_status']) {
				case '0':
					$data['is_invoice_text'] = $data['text_is_invoice_removed'];
					break;
				case '1':
					$data['is_invoice_text'] = $data['text_is_invoice_added'];
					break;
				case '2':
					$data['is_invoice_text'] = $data['text_is_invoice_passed'];
					break;
				default:
					# code...
					break;
			}
			$data['is_invoice'] = $order_info['bill_status'];
			$data['verify_status'] = $order_info['verify_status'];

			$data['reward_total'] = $this->model_customer_customer->getTotalCustomerRewardsByOrderId($order_id);

			$data['affiliate_fullname'] = $order_info['affiliate_fullname'];

			if ($order_info['affiliate_id']) {
				$data['affiliate'] = $this->url->link('marketing/affiliate/edit', 'token=' . $this->session->data['token'] . '&affiliate_id=' . $order_info['affiliate_id'], 'SSL');
			} else {
				$data['affiliate'] = '';
			}

			$data['commission'] = $this->currency->format($order_info['commission'], $order_info['currency_code'], $order_info['currency_value']);

			$this->load->model('marketing/affiliate');

			$data['commission_total'] = $this->model_marketing_affiliate->getTotalTransactionsByOrderId($order_id);

			$this->load->model('localisation/order_status');

			$order_status_info = $this->model_localisation_order_status->getOrderStatus($order_info['order_status_id']);

			if ($order_status_info) {
				$data['order_status'] = $order_status_info['name'];
			} else {
				$data['order_status'] = '';
			}

			$data['order_statuses'] = $this->model_localisation_order_status->getOrderStatuses();

			$data['order_status_id'] = $order_info['order_status_id'];

			$data['account_custom_field'] = $order_info['custom_field'];

			$finance_group = $this->config->get('config_finance_user');
			$groupId = $this->user->getGroupId();
			$data['have_permission'] = false;
			$has_pay = $order_info['is_pay'];
			if(($groupId == $finance_group)&&($order_info['order_status_id']==2)&&(!$has_pay)){
				$data['have_permission'] = true;
			}

			// Custom Fields
			$this->load->model('customer/custom_field');

			$data['account_custom_fields'] = array();

			$filter_data = array(
				'sort'  => 'cf.sort_order',
				'order' => 'ASC',
			);

			$custom_fields = $this->model_customer_custom_field->getCustomFields($filter_data);

			foreach ($custom_fields as $custom_field) {
				if ($custom_field['location'] == 'account' && isset($order_info['custom_field'][$custom_field['custom_field_id']])) {
					if ($custom_field['type'] == 'select' || $custom_field['type'] == 'radio') {
						$custom_field_value_info = $this->model_customer_custom_field->getCustomFieldValue($order_info['custom_field'][$custom_field['custom_field_id']]);

						if ($custom_field_value_info) {
							$data['account_custom_fields'][] = array(
								'name'  => $custom_field['name'],
								'value' => $custom_field_value_info['name']
							);
						}
					}

					if ($custom_field['type'] == 'checkbox' && is_array($order_info['custom_field'][$custom_field['custom_field_id']])) {
						foreach ($order_info['custom_field'][$custom_field['custom_field_id']] as $custom_field_value_id) {
							$custom_field_value_info = $this->model_customer_custom_field->getCustomFieldValue($custom_field_value_id);

							if ($custom_field_value_info) {
								$data['account_custom_fields'][] = array(
									'name'  => $custom_field['name'],
									'value' => $custom_field_value_info['name']
								);
							}
						}
					}

					if ($custom_field['type'] == 'text' || $custom_field['type'] == 'textarea' || $custom_field['type'] == 'file' || $custom_field['type'] == 'date' || $custom_field['type'] == 'datetime' || $custom_field['type'] == 'time') {
						$data['account_custom_fields'][] = array(
							'name'  => $custom_field['name'],
							'value' => $order_info['custom_field'][$custom_field['custom_field_id']]
						);
					}

					if ($custom_field['type'] == 'file') {
						$upload_info = $this->model_tool_upload->getUploadByCode($order_info['custom_field'][$custom_field['custom_field_id']]);

						if ($upload_info) {
							$data['account_custom_fields'][] = array(
								'name'  => $custom_field['name'],
								'value' => $upload_info['name']
							);
						}
					}
				}
			}

			// Custom fields
			$data['payment_custom_fields'] = array();

			foreach ($custom_fields as $custom_field) {
				if ($custom_field['location'] == 'address' && isset($order_info['payment_custom_field'][$custom_field['custom_field_id']])) {
					if ($custom_field['type'] == 'select' || $custom_field['type'] == 'radio') {
						$custom_field_value_info = $this->model_customer_custom_field->getCustomFieldValue($order_info['payment_custom_field'][$custom_field['custom_field_id']]);

						if ($custom_field_value_info) {
							$data['payment_custom_fields'][] = array(
								'name'  => $custom_field['name'],
								'value' => $custom_field_value_info['name'],
								'sort_order' => $custom_field['sort_order']
							);
						}
					}

					if ($custom_field['type'] == 'checkbox' && is_array($order_info['payment_custom_field'][$custom_field['custom_field_id']])) {
						foreach ($order_info['payment_custom_field'][$custom_field['custom_field_id']] as $custom_field_value_id) {
							$custom_field_value_info = $this->model_customer_custom_field->getCustomFieldValue($custom_field_value_id);

							if ($custom_field_value_info) {
								$data['payment_custom_fields'][] = array(
									'name'  => $custom_field['name'],
									'value' => $custom_field_value_info['name'],
									'sort_order' => $custom_field['sort_order']
								);
							}
						}
					}

					if ($custom_field['type'] == 'text' || $custom_field['type'] == 'textarea' || $custom_field['type'] == 'file' || $custom_field['type'] == 'date' || $custom_field['type'] == 'datetime' || $custom_field['type'] == 'time') {
						$data['payment_custom_fields'][] = array(
							'name'  => $custom_field['name'],
							'value' => $order_info['payment_custom_field'][$custom_field['custom_field_id']],
							'sort_order' => $custom_field['sort_order']
						);
					}

					if ($custom_field['type'] == 'file') {
						$upload_info = $this->model_tool_upload->getUploadByCode($order_info['payment_custom_field'][$custom_field['custom_field_id']]);

						if ($upload_info) {
							$data['payment_custom_fields'][] = array(
								'name'  => $custom_field['name'],
								'value' => $upload_info['name'],
								'sort_order' => $custom_field['sort_order']
							);
						}
					}
				}
			}

			// Shipping
			$data['shipping_custom_fields'] = array();

			foreach ($custom_fields as $custom_field) {
				if ($custom_field['location'] == 'address' && isset($order_info['shipping_custom_field'][$custom_field['custom_field_id']])) {
					if ($custom_field['type'] == 'select' || $custom_field['type'] == 'radio') {
						$custom_field_value_info = $this->model_customer_custom_field->getCustomFieldValue($order_info['shipping_custom_field'][$custom_field['custom_field_id']]);

						if ($custom_field_value_info) {
							$data['shipping_custom_fields'][] = array(
								'name'  => $custom_field['name'],
								'value' => $custom_field_value_info['name'],
								'sort_order' => $custom_field['sort_order']
							);
						}
					}

					if ($custom_field['type'] == 'checkbox' && is_array($order_info['shipping_custom_field'][$custom_field['custom_field_id']])) {
						foreach ($order_info['shipping_custom_field'][$custom_field['custom_field_id']] as $custom_field_value_id) {
							$custom_field_value_info = $this->model_customer_custom_field->getCustomFieldValue($custom_field_value_id);

							if ($custom_field_value_info) {
								$data['shipping_custom_fields'][] = array(
									'name'  => $custom_field['name'],
									'value' => $custom_field_value_info['name'],
									'sort_order' => $custom_field['sort_order']
								);
							}
						}
					}

					if ($custom_field['type'] == 'text' || $custom_field['type'] == 'textarea' || $custom_field['type'] == 'file' || $custom_field['type'] == 'date' || $custom_field['type'] == 'datetime' || $custom_field['type'] == 'time') {
						$data['shipping_custom_fields'][] = array(
							'name'  => $custom_field['name'],
							'value' => $order_info['shipping_custom_field'][$custom_field['custom_field_id']],
							'sort_order' => $custom_field['sort_order']
						);
					}

					if ($custom_field['type'] == 'file') {
						$upload_info = $this->model_tool_upload->getUploadByCode($order_info['shipping_custom_field'][$custom_field['custom_field_id']]);

						if ($upload_info) {
							$data['shipping_custom_fields'][] = array(
								'name'  => $custom_field['name'],
								'value' => $upload_info['name'],
								'sort_order' => $custom_field['sort_order']
							);
						}
					}
				}
			}

			$data['ip'] = $order_info['ip'];
			$data['sign_price'] = $order_info['sign_price'];
			$data['conform_price'] = $order_info['conform_price'];
			$data['verify_status'] = $order_info['verify_status'];
			// var_dump($data['verify_status']);
			$data['forwarded_ip'] = $order_info['forwarded_ip'];
			$data['user_agent'] = $order_info['user_agent'];
			$data['accept_language'] = $order_info['accept_language'];

			// Additional Tabs
			$data['tabs'] = array();

			$this->load->model('extension/extension');

			$content = $this->load->controller('payment/' . $order_info['payment_code'] . '/order');

			if ($content) {
				$this->load->language('payment/' . $order_info['payment_code']);

				$data['tabs'][] = array(
					'code'    => $order_info['payment_code'],
					'title'   => $this->language->get('heading_title'),
					'content' => $content
				);
			}

			$extensions = $this->model_extension_extension->getInstalled('fraud');

			foreach ($extensions as $extension) {
				if ($this->config->get($extension . '_status')) {
					$this->load->language('fraud/' . $extension);

					$content = $this->load->controller('fraud/' . $extension . '/order');

					if ($content) {
						$data['tabs'][] = array(
							'code'    => $extension,
							'title'   => $this->language->get('heading_title'),
							'content' => $content
						);
					}
				}
			}

			// API login
			$this->load->model('user/api');

			$api_info = $this->model_user_api->getApi($this->config->get('config_api_id'));

			if ($api_info) {
				$data['api_id'] = $api_info['api_id'];
				$data['api_key'] = $api_info['key'];
				$data['api_ip'] = $this->request->server['REMOTE_ADDR'];
			} else {
				$data['api_id'] = '';
				$data['api_key'] = '';
				$data['api_ip'] = '';
			}

			$data['header'] = $this->load->controller('common/header');
			$data['column_left'] = $this->load->controller('common/column_left');
			$data['footer'] = $this->load->controller('common/footer');

			$this->response->setOutput($this->load->view('sale/edit_order_info.tpl', $data));
		} else {
			$this->load->language('error/not_found');

			$this->document->setTitle($this->language->get('heading_title'));

			$data['heading_title'] = $this->language->get('heading_title');

			$data['text_not_found'] = $this->language->get('text_not_found');

			$data['breadcrumbs'] = array();

			$data['breadcrumbs'][] = array(
				'text' => $this->language->get('text_home'),
				'href' => $this->url->link('common/dashboard', 'token=' . $this->session->data['token'], 'SSL')
			);

			$data['breadcrumbs'][] = array(
				'text' => $this->language->get('heading_title'),
				'href' => $this->url->link('error/not_found', 'token=' . $this->session->data['token'], 'SSL')
			);

			$data['header'] = $this->load->controller('common/header');
			$data['column_left'] = $this->load->controller('common/column_left');
			$data['footer'] = $this->load->controller('common/footer');

			$this->response->setOutput($this->load->view('error/not_found.tpl', $data));
		}
	}else{
		$post = $this->request->post['obj'];
		$old_order_id = $this->request->get['order_id'];

		//判断拿到初始订单
		$order_info = $this->model_sale_order->getOrder($old_order_id);

		if($order_info['order_status_id']){
			/*if($order_info['parent_id']){
				$src_order_id = $order_info['parent_id'];
			}else{
				$src_order_id = $old_order_id;
			}*/

			$src_order_id = $old_order_id;

			$src_map['order_id'] = $src_order_id;
			$src_map['code'] = 'sub_total';
			$src_order_info = M('order_total')->where($src_map)->getfield('value');
			$src_total = floatval($src_order_info);

			//拿到商品的信息
			$products = $this->model_sale_order->getOrderProducts($src_order_id);
			$old_products = $this->model_sale_order->getOrderProducts($old_order_id);

			$new_products = $products;
			$new_total = 0;
            /* 循环降维
			foreach ($old_products as $key1 => $value1) {
				foreach($post as $key2 => $value2){
					if($value1['order_product_id']==$value2['id']){
                        $post[$key2]['name'] = $value1['name'];//post不再传递商品名称信息，避免订单包含大量商品时，post值超过http限制，丢数据造成订单信息异常。
						//如果小于0设置为0
						$tmp_num = $value2['num']<0?0:$value2['num'];
						$new_total+= $tmp_num*$value1['price'];
						$new_products[$key1]['quantity'] = $tmp_num;
						if($tmp_num == 0){
							$this->model_sale_order->setOrderProductLackQuantityZero($value1['order_product_id']);
						}
					}
				}
			}
            // */
            //*
            $temp = array();
            foreach ($post as $k=>$v) {
                $temp[$v['id']] = $v;
            }
            $post = $temp;//重写post数组，把pk作为数组的key，便于循环降维

            foreach ($old_products as $key1 => $value1) {
                $value2 = $post[$value1['order_product_id']];
                $post[$value1['order_product_id']]['name'] = $value1['name'];//post不再传递商品名称信息，避免订单包含大量商品时，post值超过http限制，丢数据造成订单信息异常。
                //如果小于0设置为0
                $tmp_num = $value2['num']<0?0:$value2['num'];
                $new_total+= $tmp_num*$value1['price'];
                $new_products[$key1]['quantity'] = $tmp_num;
                if($tmp_num == 0){
                    $this->model_sale_order->setOrderProductLackQuantityZero($value1['order_product_id']);
                }
            }
            // */

			$postStatus = $this->request->post['status'];

			if(round($new_total,2)<=round($src_total,2)){ //金额不能小于原来
				$new_order_id = $this->model_sale_order->updateOrder($old_order_id,$postStatus);
				$this->model_sale_order->updateOrderProduct($new_order_id,$new_products);//7s
				$this->model_sale_order->updateOrderTotal($new_order_id,$new_total);
				$this->model_sale_order->copyOrderHistory($old_order_id,$new_order_id);//20s
				$username = $this->user->getUserName();
				foreach ($post as $key => $value) {
					if($value['num']!=$value['oldnum']){
							$comment = $username.'将'.$value['name'].'的数量由'.$value['oldnum'].'改为'.$value['num'];
							$this->model_sale_order->addOrderHistory($new_order_id,$comment,$order_info['order_status_id']);
					}
				}
				$event_data = array(
					'old_order_id' => $old_order_id,
					'new_order_id' => $new_order_id,
					);
				//$this->event->trigger('so.product.addstock', $event_data);//维护老版本库存，废弃
				$json['success'] = '修改成功';
				$json['order_id'] = $new_order_id;
			}else{
				$json['error'] = '金额超出原金额';
			}
		}else{
			$json['error'] = '此订单已作废';
		}

		$this->response->addHeader('Content-Type: application/json');
		$this->response->setOutput(json_encode($json));
	}

  }
  public function editsign(){
  	$this->load->model('sale/order');
	$post = $this->request->post['obj'];
	$order_id = $this->request->get['order_id'];
	// var_dump($order_id);

	//判断拿到初始订单
	$order_info = $this->model_sale_order->getOrder($order_id);

	if($order_info['order_status_id']){

		
		//优惠金额
		$couponprice = $this->model_sale_order->getOrderTotals($order_id);
		$coupon_price = 0;
		foreach ($couponprice as $key => $value) {
			// var_dump($value);
			if ($value['value']<0) {
				$coupon_price +=$value['value'];
			}
		}
		$username = $this->user->getUserName();
		// var_dump($coupon_price);
		$signtotal=0;
        foreach ($post as $k=>$v) {
        	// var_dump($v);die();

            if ($v['type']==1) {
            	$opinfo = $this->model_sale_order->updateOrProduct($v['num'],$v['id']);
            	// var_dump($opinfo['sign_quantity']);
            	// var_dump($opinfo['price']);

            	$signtotal += $opinfo['sign_quantity']*$opinfo['price'];
				if($v['num']!=$v['oldnum']){

					$comment = $username.'将'.$opinfo['name'].'的数量由'.$v['oldnum'].'改为'.$v['num'];
					$this->model_sale_order->addOrderHistory($order_id,$comment,$order_info['order_status_id']);
				}
            	
            }else{
            	$opginfo =$this->model_sale_order->updateOrProductG($v['num'],$v['pgid']);
            	// var_dump($opginfo);
            	

            	$signtotal += $opginfo['sign_quantity']*$opginfo['price'];
            	if($v['num']!=$v['oldnum']){
            		// var_dump($v);
            		// var_dump($v['pgid']);

					$comment = $username.'将'.$opginfo['name'].'的数量由'.$v['oldnum'].'改为'.$v['num'];
					$this->model_sale_order->addOrderHistory($order_id,$comment,$order_info['order_status_id']);
				}
            }
        }

		$postStatus = $this->request->post['status'];
		// $this->model_sale_order->updateOrderProductSign($new_order_id,$new_products);//7s
		// var_dump($signtotal);
  //           	var_dump($coupon_price);
		$signtotal +=$coupon_price;
          // var_dump($signtotal);

		 $this->model_sale_order->signupdateOrder($order_id,$postStatus,$signtotal);
		//$this->event->trigger('so.product.addstock', $event_data);//维护老版本库存，废弃
		$json['success'] = '修改成功';
		$json['order_id'] = $order_id;
		
	}else{
		$json['error'] = '此订单已作废';
	}

	$this->response->addHeader('Content-Type: application/json');
	$this->response->setOutput(json_encode($json));


  }
  /*编辑商品订单*/

  public function editProductInitiai($event_data){
  	$old_order_id = $event_data['old_order_id'];
  	$new_order_id = $event_data['new_order_id'];

  	$this->load->model('sale/order');

  	$this->model_sale_order->editProductInitiai($old_order_id,1);
  	$this->model_sale_order->editProductInitiai($new_order_id,0);
  }

    /*
     * 在线支付退款，重写逻辑，保留完成接口调用日志，发短信通知用户和业务员
     * @author sonicsjh
     */
    public function refundmoney(){
        $orderId = intval($this->request->post['order_id']);
        $type = intval($this->request->post['type']);
        $returnMoney = floatval($this->request->post['money']);

        if (0 == $orderId) {
            $json['error'] = '错误的订单编号，退款失败。';
        }else if ($returnMoney < 0.01) {
            $json['error'] = '退款金额错误，退款失败。';
        }else{
            $this->load->helper('yijiSignHelper');
            $this->load->helper('dto/fastPayTradeRefund');
            $this->load->helper('YijipayClient');
            //创建退款记录
            $this->load->model('sale/order');
            $orderOnlineRefundData = array(
                'order_id' => $orderId,
                'refund_amount' => $returnMoney,
                'type' => $type,
                'comment' => '',
                'status' => '1',
                'date_added' => date('Y-m-d H:i:s'),
            );
            $OORPK = $this->model_sale_order->addOrderOnlineRefund($orderOnlineRefundData);
            //创建退款记录
            $objReq = new fastPayTradeRefund();
            //请求公共部分
            $objReq->setNotifyUrl('http://m.bhz360.com/index.php?route=payment/yiji_refund_v2');//自定义异步回调，记录完整支付日志
            $objReq->setPartnerId($config['partnerId']);
            $YJFPK = 'BHZ2017OOR'.substr(time(), -10).$OORPK;//基于退款表PK的流水号
            $objReq->setOrderNo($YJFPK);
            $objReq->setMerchOrderNo($YJFPK);
            $objReq->setSignType("MD5");
            //构建交易参数
            $objReq->settradeNo($this->model_sale_order->gettradeNo($orderId));
            $objReq->setrefundAmount($returnMoney);
            if (2 == $type) {
                $objReq->setrefundReason('春节抽奖返现');
            }else{
                $objReq->setrefundReason('缺货退款');
            }
            //构建请求
            $config = $this->getConfig();
            $client = new YijiPayClient($config);
            $response = $client->execute($objReq);

            $params = json_decode($response, true);
            $status = 3;
            $json['error'] = '验签失败';
            if ($client->verify($params)){
                if ($params['success'] && ('EXECUTE_SUCCESS' == $params['resultCode'] || 'EXECUTE_PROCESSING' == $params['resultCode'])) {
                    $status = 1;
                    $json['success'] = '退款申请成功，银行处理中。';
                    $this->_sendSmsForRefundOrder($orderId, $returnMoney, $type);//调用短信接口发送退款通知短信
                    if (1 == $type) {
                        $this->model_sale_order->clearReturnMoneyInOrder();
                    }
                }else{
                    $json['error'] = $params['resultMessage'];
                }
            }
            //更新退款记录的同步返回信息
            $orderOnlineRefundData = array(
                'status' => $status,
                'return_params' => $response,
            );
            $this->model_sale_order->updateOrderOnlineRefund($OORPK, $orderOnlineRefundData);
            //更新退款记录的同步返回信息
        }
        $this->response->addHeader('Content-Type: application/json');
        $this->response->setOutput(json_encode($json));
    }

    /*
     * 发送通知短信
     */
    protected function _sendSmsForRefundOrder($orderId, $returnMoney, $type) {
        $this->load->model('sale/order');
        $this->load->model('tool/sms_log');
        $info = $this->model_sale_order->getCAndUInfo($orderId);

        $this->load->helper('sms');
        $sms = new smsHelper();
        $appId = $this->config->get('tianyi_appid');
        $appSecret = $this->config->get('tianyi_appsecret');
        if (2 == $type) {
            $templateId = '91553845';//抽奖返现模块，详见 http://open.189.cn/
        }else{
            $templateId = '91553440';//缺货退款模块，详见 http://open.189.cn/
        }
        //$phone = '';
        $tempParam = array(
            'user' => $info['CName'],
            'orderId' => $orderId,
            'amount' => $returnMoney,
        );
        $retC = $sms->sendSms($appId, $appSecret, $templateId, $info['CTel'], $tempParam);//客户短信通知
        $this->model_tool_sms_log->saveData($retC['smsLog']);
        $retU = $sms->sendSms($appId, $appSecret, $templateId, $info['UTel'], $tempParam);//业务员短信通知
        $this->model_tool_sms_log->saveData($retU['smsLog']);
        if (2 == $type) {
            //获取区域经理手机号码
            switch ($info['logcenter_id']) {
                case 4://苏南（苏锡常）
                    $retU = $sms->sendSms($appId, $appSecret, $templateId, '13382214258', $tempParam);//陈保宋
                    $this->model_tool_sms_log->saveData($retU['smsLog']);
                    break;
                case 5://南通
                    $retU = $sms->sendSms($appId, $appSecret, $templateId, '13862951387', $tempParam);//张小冬
                    $this->model_tool_sms_log->saveData($retU['smsLog']);
                    break;
                case 13://温州
                    $retU = $sms->sendSms($appId, $appSecret, $templateId, '13780179189', $tempParam);//任奎
                    $this->model_tool_sms_log->saveData($retU['smsLog']);
                    break;
                case 15://嘉善
                    //$retU = $sms->sendSms($appId, $appSecret, $templateId, '', $tempParam);//
                    //$this->model_tool_sms_log->saveData($retU['smsLog']);
                    break;
                case 25://台州
                    $retU = $sms->sendSms($appId, $appSecret, $templateId, '18869963787', $tempParam);//王希刚
                    $this->model_tool_sms_log->saveData($retU['smsLog']);
                    break;
            }
        }else{
            //台州区域的订单，额外发给王希刚
            if ('25' == $info['logcenter_id']) {
                $retU = $sms->sendSms($appId, $appSecret, $templateId, '18869963787', $tempParam);//王希刚电话号码
                $this->model_tool_sms_log->saveData($retU['smsLog']);
            }
        }
        $retU = $sms->sendSms($appId, $appSecret, $templateId, '13564536028', $tempParam);//财务顾俊的电话号码
        $this->model_tool_sms_log->saveData($retU['smsLog']);
    }

/*
    public function refundmoney(){
        $this->load->helper('yijiSignHelper');
        $this->load->helper('dto/fastPayTradeRefund');
        $this->load->helper('YijipayClient');

        $objReq = new fastPayTradeRefund();
        //请求公共部分
        $objReq->setNotifyUrl('http://m.bhz360.com/index.php?route=payment/yiji_refund');
        if(isset($this->request->post['order_id'])){
            $order_id = $this->request->post['order_id'];
        }else{
            $order_id = '0';
        }
        $objReq->setPartnerId($config['partnerId']);
        $objReq->setOrderNo('BHZ2017'.time().$order_id);
        $objReq->setMerchOrderNo($this->getBefstr().$order_id);
        $objReq->setSignType("MD5");
        $this->load->model('sale/order');
        $tradeNo = $this->model_sale_order->gettradeNo($order_id);
        //构建交易参数
        $objReq->settradeNo($tradeNo);
        $objReq->setrefundAmount($this->request->post['money']);
        $objReq->setrefundReason('无货退款');
        //构建请求
        $config = $this->getConfig();
        $client = new YijiPayClient($config);
        $response = $client->execute($objReq);
        $params = json_decode($response,true);
        if($client->verify($params)){
            if($params['success']){
                if('EXECUTE_PROCESSING'== $params['resultCode']){
                    $json['success'] = '成功退款'.$this->request->post['money'].'元,银行正在处理中..';
                    $this->model_sale_order->addUsertradeNo($order_id,$this->request->post['money']);
                }else if('EXECUTE_SUCCESS'== $params['resultCode']){
                    $json['success'] = '已退款成功的订单';
                }
            }else{
                $json['error'] = $params['resultMessage'];
            }
        }else{
            $json['error'] = '验签失败';
        }
        $this->response->addHeader('Content-Type: application/json');
        $this->response->setOutput(json_encode($json));
    }
*/
   public function getConfig(){
        return array(
        'partnerId' => '20161201020011981315', //商户ID
        'md5Key' => 'db3d0a81a79b6832c439bbf5ec92b77c', //商户Key

        //网关
        'gatewayUrl' => "https://api.yiji.com/gateway.html" //生产环境
        // 'gatewayUrl' => "https://openapi.yijifu.net/gateway.html"	//测试环境
        );
    }

	public function getBefstr(){
		 return $order_befstr='BHZ2017REFUND57'.substr(time(),'-5');
    }

    //仅限财务（顾俊）账号使用，导出所有区域已收货未收款订单列表
    public function exportReceiptWithOutPay() {
        $this->load->model('sale/order');
        $orderList = $this->model_sale_order->getReceiptWithOutPay();
        $exportCols = array(
            'order_id'          => '订单号',
            'shipping_fullname' => '收货人',
            'shipping_company'  => '超市名称',
            'shipping_address'  => '收货地址',
            'date_added'        => '下单时间',
            'o_total'           => '订单总价',
            'user'              => '业务员',
            'receive_date'      => '首次签收时间',
            'receive_total'     => '已签收总额',
        );

        $this->load->helper('export');
        prepareDownloadExcel($orderList, array_values($exportCols), array_keys($exportCols), 'Orders_ReceiptWithOutPay');
    }
}
